我有两个要根据它们的索引合并的数据框:
df1:
stock1 ... stock n
(2, 2012-10-21 17:00:00) -8.14 ... 7.85
(3, 2012-10-21 17:00:00) -5.05 ... 4.61
(6, 2012-10-21 17:00:00) -7.29 ... 7.10
(7, 2012-10-21 17:00:00) -8.37 ... 7.99
(8, 2012-10-21 17:00:00) -4.55 ... 4.31
df2:
level_0 ... dummy
(1, Timestamp('2012-11-30 12:00:00')) 82729 ... 1
(1, Timestamp('2012-11-30 12:05:00')) 82758 ... 1
(1, Timestamp('2012-11-30 12:10:00')) 82787 ... 0
(1, Timestamp('2012-11-30 12:15:00')) 82816 ... 0
(2, Timestamp('2012-11-30 12:20:00')) 82845 ... 1
我想基于索引合并它们。当我在Spyder中作为单独的窗口打开df1时,我看到索引的格式与df2中的相同(带有“时间戳记”),但是当我“打印”它时,却看不到这一部分。
当我尝试下面的代码时,我收到一个空的数据框,但是,我手动检查并且有相同的索引值。
result=df1.merge(df2,how='inner',left_index=True,right_index=True) OR
result=merge(df1, df2[['dummy']], left_index=True, right_index=True)
我还通过以下方法检查了两个索引是否具有1级:
df1.index.nlevels
Out[1099]: 1
df2.index.nlevels
Out[1100]: 1
我该如何解决?
我还尝试过更改df2索引以匹配df1索引,如下所示:
df2=df2.reset_index()
df2['index'] = df2['index'].astype('str')
df2['index']=df2['index'].str.replace("Timestamp","")
df2['index']=df2['index'].str.replace("'","")
df2['index'] = df2['index'].str[:-1]
df2['index1']=df2['index'].str.replace(" \("," ")
df2=df2.set_index('index1')
但在尝试合并时再次收到一个空矩阵。
我该如何解决?