pandas DataFrame合并求和列 [英] Pandas DataFrame merge summing column

查看:416
本文介绍了 pandas DataFrame合并求和列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试合并两个DataFrames求和列值.

I'm trying to merge two DataFrames summing columns value.

>>> print(df1)
   id name  weight
0   1    A       0
1   2    B      10
2   3    C      10

>>> print(df2)
   id name  weight
0   2    B      15
1   3    C      10

在合并公用列中的相似值时,我需要对weight个值求和.

I need to sum weight values during merging for similar values in the common column.

merge = pd.merge(df1, df2, how='inner')

所以输出将类似于以下内容.

So the output will be something like following.

   id name  weight
1   2    B      25
2   3    C      20

推荐答案

In [41]: pd.merge(df1, df2, on=['id', 'name']).set_index(['id', 'name']).sum(axis=1)
Out[41]: 
id  name
2   B       25
3   C       20
dtype: int64

这篇关于 pandas DataFrame合并求和列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆