【问题标题】:Formatting Pandas groupby() for merge格式化 Pandas groupby() 以进行合并
【发布时间】:2017-07-24 17:55:37
【问题描述】:

我希望有人可以帮助我完成我一直在尝试做的相对简单的事情。最近,我使用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

然后我用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() 是否有办法在我执行groupby() 之后为每个观察列出MSA.name

【问题讨论】:

  • df.groupby(['MSA.name', 'ifr.industry'])['employees'].sum().reset_index()
  • @Wen 太棒了,非常感谢!
  • 我另加一种方式,可以保存merge这一步

标签: python pandas pandas-groupby


【解决方案1】:

先试试这个df.groupby(['MSA.name', 'ifr.industry'])['employees'].sum().reset_index()

另外,这里不需要merge,使用transform

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

【讨论】:

  • 非常感谢您提供了令人难以置信的信息!
  • @danny ,很高兴能帮到你~祝你有美好的一天
猜你喜欢
  • 2021-12-15
  • 2018-02-09
  • 2017-11-03
  • 2020-06-29
  • 2014-10-17
  • 2014-11-29
  • 1970-01-01
  • 2019-10-12
  • 2022-01-15
相关资源
最近更新 更多