基于公共列对Pandas DataFrame多列值求和的实现方法
按公共列分组求和生成新DataFrame的解决方案
没问题,这事儿用Pandas的分组聚合功能就能轻松搞定,我拿你提供的样例数据一步步演示:
原始样例数据
先把你给出的DataFrame整理成表格形式方便查看:
| date | id | device | t1 | t2 | text | y1 | y2 |
|---|---|---|---|---|---|---|---|
| 2010-1-1 | 1 | pc | yes1 | I am1 | This is a test1 | 5 | 3 |
| 2010-1-1 | 1 | smart | yes1 | I am1 | This is a test1 | 6 | 4 |
| 2010-1-1 | 1 | table | yes1 | I am1 | This is a test1 | 7 | 5 |
| 2010-1-1 | 2 | pc | yes2 | I am1 | This is a test2 | 8 | 2 |
| 2010-1-1 | 2 | smart | yes2 | I am1 | This is a test2 | 8 | 3 |
| 2010-1-1 | 2 | table | yes2 | I am1 | This is a test2 | 9 | 4 |
| 2010-1-1 | 3 | pc | yes3 | I am3 | This is a test3 | 10 | 3 |
| 2010-1-1 | 3 | smart | yes3 | I am3 | This is a tes3 | 11 | 2 |
实现代码
核心思路是用groupby()指定分组的公共列(date和id),然后选择需要求和的列(y1、y2),最后调用sum()完成聚合,再用reset_index()把分组列还原成普通列:
import pandas as pd # 假设你的原始DataFrame名为df df = pd.DataFrame({ 'date': ['2010-1-1']*8, 'id': [1,1,1,2,2,2,3,3], 'device': ['pc','smart','table','pc','smart','table','pc','smart'], 't1': ['yes1','yes1','yes1','yes2','yes2','yes2','yes3','yes3'], 't2': ['I am1']*6 + ['I am3']*2, 'text': ['This is a test1']*3 + ['This is a test2']*3 + ['This is a test3', 'This is a tes3'], 'y1': [5,6,7,8,8,9,10,11], 'y2': [3,4,5,2,3,4,3,2] }) # 分组求和 result_df = df.groupby(['date', 'id'])[['y1', 'y2']].sum().reset_index()
输出结果
运行上面的代码后,得到的新DataFrameresult_df如下:
| date | id | y1 | y2 |
|---|---|---|---|
| 2010-1-1 | 1 | 18 | 12 |
| 2010-1-1 | 2 | 25 | 9 |
| 2010-1-1 | 3 | 21 | 5 |
补充说明
- 如果不需要保留分组列作为索引,
reset_index()是必须的,否则date和id会变成多级索引 - 如果你还需要保留其他非聚合列(比如
t1、t2),可以用agg()方法指定不同列的聚合规则,比如对t1取第一个值,对y1、y2求和:result_df = df.groupby(['date', 'id']).agg( t1=('t1', 'first'), t2=('t2', 'first'), y1=('y1', 'sum'), y2=('y2', 'sum') ).reset_index()
内容的提问来源于stack exchange,提问作者tktktk0711
相关产品推荐
相关产品推荐

