2017-10-19 82 views
2

我有两个数据帧:蟒蛇聚合列

df1

 A B C D 
Index 
1  0 1 1 3 
2  1 0 3 1 
3  4 0 1 1 
4  0 2 2 2 

df2

 A B 
Index 
1  1 2 
2  3 4 
3  0 0 
4  1 2 

我希望我的输出是

df_result

 A B C D 
Index 
1  1 3 1 3 
2  4 4 3 1 
3  4 0 1 1 
4  1 4 2 2 

基本上,我想汇总相似的列值,并且还包括结果的不相似的列。请注意,df1df2将始终具有相同的索引。

如何在python的熊猫图书馆中做到这一点?

回答

4

由列使用concat + groupby和聚集sum

df = pd.concat([df1, df2], axis=1).groupby(level=0, axis=1).sum() 
print (df) 
     A B C D 
Index    
1  1 3 1 3 
2  4 4 3 1 
3  4 0 1 1 
4  1 4 2 2 

df = pd.concat([df1, df2], axis=1).sum(axis=1, level=0) 
print (df) 
     A B C D 
Index    
1  1 3 1 3 
2  4 4 3 1 
3  4 0 1 1 
4  1 4 2 2 
+0

这是真的快 – Dark

+1

我有你开始键入答案的问题张贴之前;-) – MaxU

+1

即使我有同样的感觉 – Dark

2

您可以使用addfill_value

In [4336]: df1.add(df2, fill_value=0) 
Out[4336]: 
     A B C D 
Index 
1  1 3 1.0 3.0 
2  4 4 3.0 1.0 
3  4 0 1.0 1.0 
4  1 4 2.0 2.0 

或者使用reindex

In [4341]: df1 + df2.reindex(columns=df1.columns, fill_value=0) 
Out[4341]: 
     A B C D 
Index 
1  1 3 1 3 
2  4 4 3 1 
3  4 0 1 1 
4  1 4 2 2