合并具有相同索引的数据并删除不具有相同索引的数据

时间:2019-10-08 13:59:19

标签: python pandas merge

dataFrame 1:

index                    col1 
03-05-2018 12:00:00         3   
03-05-2018 13:00:00         4    
03-05-2018 14:00:00         3       
03-05-2018 15:00:00         3  
.......                    ..    

dataFrame2

index                   col2 
03-05-2018 12:00:00        1    
03-05-2018 13:00:00        3    
03-05-2018 13:30:00        4    
03-05-2018 14:30:00        2    
03-05-2018 15:00:00        3   
.....                     ..

我想合并这些数据框并删除索引不匹配的值:

dataFrame 3:

index                    col1 col2 
03-05-2018 12:00:00         3    1  
03-05-2018 13:00:00         4    3   
03-05-2018 15:00:00         3    3  
.........                  ..   .. 

是否有类似pd.merge的功能来实现这一目标? (这是一个熊猫数据框,索引是DateTime对象) 谢谢!

编辑:我使用了pd.merge(dataFrame1,dataFrame2,how ='inner',on ='index',left_index = True,right_index = True),但出现错误“无法将类型'Timestamp'与类型' int”。我真的确定两个索引都是时间戳

1 个答案:

答案 0 :(得分:-1)

我只会执行inner。当inner值匹配时,on联接基本上执行联接,否则将其删除(出于该问题的目的将其删除)。

a = {'index':['A','C','D','G'],'col1':[3,4,3,3]}
b = {'index':['A','B','C','E','G'],'col2':[1,4,3,2,3]}
df_1 = pd.DataFrame(a)
df_2 = pd.DataFrame(b)
df_3 = df_1.merge(df_2,how='inner',on='index')
print(df_3)

输出:

  index  col1  col2
0     A     3     1
1     C     4     3
2     G     3     3