python - 熊猫 groupby 并添加组的总和
问题描述
A B C D
1 foo 12 California
2 foo 22 California
3 bar 8 Rhode Island
4 bar 32 Rhode Island
Required output
A B C D
1 foo 12 California
2 22 California
foo Total 34
3 bar 8 Rhode Island
4 32 Rhode Island
bar Total 40
想要在每组的末尾添加总共的数字列
解决方案
这里有两种方法。
使用groupy
+ apply
:
(df.set_index('A')
.groupby('B', as_index=False, sort=False)
.apply(lambda d: pd.concat([d, d['C'].agg({'Total': 'sum'}).to_frame()]))
.droplevel(0).rename_axis('A')
.reset_index()
.fillna('')
)
输出:
A B C D
0 1 foo 12 California
1 2 foo 22 California
2 Total 34
3 3 bar 8 Rhode Island
4 4 bar 32 Rhode Island
5 Total 40
使用concat
和groupby
+ agg
:
(pd.concat([df,
df.groupby('B', as_index=False).agg({'A': lambda x: 'Total', 'C': 'sum'})
])
.sort_values(by=['B', 'A'])
.assign(B=lambda d: d['B'].mask(d['A'].eq('Total')))
.fillna('')
)
输出:
A B C D
2 3 bar 8 Rhode Island
3 4 bar 32 Rhode Island
0 Total 40
0 1 foo 12 California
1 2 foo 22 California
1 Total 34
推荐阅读
- python - tensorflow-gpu 从 systemd 服务初始化失败
- c# - 无法删除对象,因为在删除项目时ObjectStateManager错误中找不到
- asp.net - 将 ZK 考勤设备的数据与 Web 应用程序集成和同步
- c++ - 如何使循环帐户多次出现?
- android - 如何让 StringRequestVolley 等待响应?
- c# - 为什么 ArcGIS Runtime SDK for .Net 同步地理数据库异常抛出“”
- r - 如何将外生输入添加到 nnetTs 函数?
- java - Kafka AVRO消费者端如何丢弃AVRO数据的默认值字段?
- javascript - 如何动态创建属性并为其添加值?
- delphi - 将 PNG 资源加载到 TGPImage