2016-10-10 62 views
2

我想在多个列上执行熊猫合并,其中一列是索引列。熊猫 - 如何在多个列上进行合并,包括索引

下面是示例dataframes:

df1 = pd.DataFrame(np.random.rand(4,4), columns=list('ABCD')) 
    df2 = pd.DataFrame(np.random.rand(4,4), columns=list('EFGH'), index= [5,2,4,1]) 
    df1['E'] = ['hello','hello','hello','world'] 
    df2['E'] = ['world','world','hello','hello'] 

我想执行所述索引和塔E的内合并,使得它会返回仅一排:(指数,E)=(1,'你好“)。

回答

2

这是怎么回事?

In [82]: pd.merge(df1.reset_index(), df2.reset_index(), on=['index','E']).set_index('index') 
Out[82]: 
       A  B   C   D  E  F   G   H 
index 
1  0.516878 0.56163 0.082839 0.420587 hello 0.62601 0.787371 0.121979