繁体   English   中英

合并两个添加相应值的pandas数据帧

[英]Combine two pandas dataframes adding corresponding values

我有两个这样的数据帧:

df1 = pd.DataFrame({'A': [1,0,3], 'B':[0,0,1], 'C':[0,2,2]}, index =['a','b','c'])
df2 = pd.DataFrame({'A': [0,0], 'B':[2,1]}, index =['a','c'])

df1和df2:

   | A | B | C |          | A | B |    
---|---|---|---|       ---|---|---|
 a | 1 | 0 | 0 |        a | 0 | 2 |   
 b | 0 | 0 | 2 |        c | 0 | 1 |
 c | 3 | 1 | 2 |

预期的结果是:

   | A | B | C |
---|---|---|---|
 a | 1 | 2 | 0 |
 b | 0 | 0 | 2 |
 c | 3 | 2 | 2 |

我遇到了这个问题,因为任何数据帧中都可能缺少列/行(df1可能没有df2所有的列和行)

在这个问题的答案中提出这个想法 - 在Pandas中合并2个数据帧:加入一些列,总结其他列

因为在你的情况下,索引是常见的索引,你可以使用pandas.concat()为两个DataFrames,然后根据索引使用DataFrame.groupby,然后DataFrame.groupby进行求和。 示例 -

In [27]: df1
Out[27]:
   A  B  C
a  1  0  0
b  0  0  2
c  3  1  2

In [28]: df2
Out[28]:
   A  B
a  0  2
c  0  1

In [29]: pd.concat([df1,df2]).groupby(level=0).sum()
Out[29]:
   A  B  C
a  1  2  0
b  0  0  2
c  3  2  2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM