我有两个数据框,我想将它们按列(axis=1)与内部联接连接起来。其中一个数据帧有一些重复的索引,但行不重复,我不想丢失其中的数据:
df1 = pd.DataFrame([{'a':1,'b':2},{'a':1,'b':3},{'a':2,'b':4}],
columns = ['a','b']).set_index('a')
df2 = pd.DataFrame([{'a':1,'c':5},{'a':2,'c':6}],columns = ['a','c']).set_index('a')
>>> df1
b
a
1 2
1 3
2 4
8 9
>>> df2
c
a
1 5
2 6
默认concat
行为是用 NaN 填充缺失值:
>>> pd.concat([df1,df2])
b c
a
1 2 NaN
1 3 NaN
2 4 NaN
1 NaN 5
2 NaN 6
我想保留 df1 中的重复索引并用 df2 中的重复值填充它们,但在 pandas 0.13.1 中,列上的内部联接会产生错误。在更新版本的 pandas concat 中,我想要做的事情:
>>> pd.concat([df1, df2], axis=1, join='inner')
b c
a
1 2 5
1 3 5
2 4 6
实现我想要的结果的最佳方法是什么?有分组解决方案吗?或者也许我不应该使用concat
at all?