python - Python - groupby sum map to another dataframe
问题描述
My dataframe A:
id groupA groupB groupC groupD groupE ...
001 0 0 0 0 0
002 0 0 0 0 0
003 0 0 0 0 0
...
Dataframe B:
id value count
001 groupA 2
002 groupB 1
001 groupB 3
001 groupC 1
003 groupC 2
002 groupA 1
dfB.groupby(['id', 'value'])['count'].sum()
By running this groupby I get:
id value
1 groupA 2
groupB 3
groupC 1
2 groupA 1
groupB 1
3 groupC 2
Name: count, dtype: int64
I was trying to transform this result to a dataframe and map it back to dataframe A, but it didn't work out.
My ideal dataframe Aoutput is:
id groupA groupB groupC groupD groupE ...
001 2 3 1 0 0
002 1 1 0 0 0
003 0 0 2 0 0
...
解决方案
用单线链做reindex
dfb.groupby(['id', 'value'])['count'].sum().\
unstack(fill_value=0).\
reindex(columns=dfa.columns,index=dfa.id,fill_value=0).\
drop('id',1)
groupA groupB groupC groupD groupE
id
1 2 3 1 0 0
2 1 1 0 0 0
3 0 0 2 0 0
推荐阅读
- git - 如何将原始存储库的拉取请求合并到分叉存储库中?
- ios - 如何在 Moya 请求中通过 POST 请求传递原始 JSON 正文
- html - 如何在一行中放置不同尺寸的弹性物品?
- localization - 如何在 i18next 中处理粘着性语言(例如土耳其语、日语等)的不同后缀
- umbraco - Umbraco 版本 8 | 在哪里更改控制器以验证自定义模型?
- python - Python当生成器'yield'遇到'random'时
- bash - 为什么 bash 会修剪/更改输出中的字母顺序?
- reactjs - 如何使接收所有 3 个值的 useReducer 的文档示例工作?
- powerbi - Power BI:根据去年的方差百分比计算方差总和
- flutter - 如何在 VS Code 中将命令行参数传递给 Web 调试会话