python - 格式化 Pandas groupby() 以进行合并

标签 python pandas pandas-groupby

我希望有人能帮助我做一些我一直在尝试做的相对简单的事情。最近,我用了groupby总结我的df中的不同群体,如下所示:

                      MSA.name ifr.industry
0   Abilene, TX Metro Area           90
1   Abilene, TX Metro Area            P
2   Abilene, TX Metro Area           90
3   Abilene, TX Metro Area            F
4   Abilene, TX Metro Area           90
5   Abilene, TX Metro Area           90
6   Abilene, TX Metro Area           90
7   Abilene, TX Metro Area           90

然后,我将各个行业的员 worker 数相加为 df.groupby(['MSA.name', 'ifr.industry'])['employees'].sum()

MSA.name               ifr.industry        employees  
Abilene, TX Metro Area 10-12               720
                       13-15                70
                       16                   87
                       17-18                54
                       20-21                77
                       22                  403
                       23                  324
                       24                  383
                       25                  701
                       28                  310
                       29                  198
                       30                  233

但是,我想将其合并回原来的 df ,但我不知道如何轻松做到这一点。我想知道是否有办法 groupby()将列出MSA.name对于我执行 groupby() 后的每一次观察.

最佳答案

首先尝试一下df.groupby(['MSA.name', 'ifr.industry'])['employees'].sum().reset_index()

此外,您不需要在这里merge,使用transform

df['sum']=df.groupby(['MSA.name', 'ifr.industry'])['employees'].transform(sum)

关于python - 格式化 Pandas groupby() 以进行合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45287048/

相关文章:

python - Django 通过多个过滤多对多

python - 通过从另一个 csv 中提取值来附加一个 csv

python - 加速数据帧从字典生成代码

python - Pandas groupby 多个聚合,不包括焦点组

python - 将分组后的列的多个值合并到python pandas中的一列中

python - Werkzeug 属性错误 : 'module' object has no attribute 'InteractiveInterpreter'

python - Matlab 相当于 Python Panda 的数据类型

python - 带 Pandas 的箱线图、groupby、子图、计算/描述性统计、聚合

python - 如何聚合两个集合,其中一个集合的字段大于另一个集合

python - Plotly:如何使用 plotly express 为具有多个组的条形图设置动画?