Pandas中的分组总计

huangapple go评论72阅读模式
英文:

Group-wise total in Pandas

问题

我有一个类似下面的pandas表格,已经使用groupby得到了如下的Groups 0, 1和2:

Group 0 Group 1 Group 2 Count
A X1 577.5000 6
894.8700 2
X2 2697.3100 48
2697.3100 1
B3 2697.3100 30
B C12 34.2700 9
39.2700 3

我想在pandas中按组得到如下的总计:

Group 0 Group 1 Group 2 Count Group 1 Count 总计
A X1 577.5000 6 8
894.8700 2 8
X2 2697.3100 48 49
2697.3100 1 49
B3 2697.3100 30 30
B C12 34.2700 9 12
39.2700 3 12
英文:

I have a pandas table like below with groupby applied to get Groups 0, 1 and 2 as follows:

Group 0 Group 1 Group 2 Count
A X1 577.5000 6
894.8700 2
X2 2697.3100 48
2697.3100 1
B3 2697.3100 30
B C12 34.2700 9
39.2700 3

I would like to get group wise total in pandas like below:

Group 0 Group 1 Group 2 Count Group 1 Total by Count
A X1 577.5000 6 8
894.8700 2 8
X2 2697.3100 48 49
2697.3100 1 49
B3 2697.3100 30 30
B C12 34.2700 9 12
39.2700 3 12

I am able to calculate cumulative sum using df.groupby(level=[0,1]).cumsum() but now sure if there is a way to achieve this.

答案1

得分: 2

你可以使用`groupby.transform`来对分组进行`sum`调用的转换
英文:

You can use groupby.transform to transform a sum call over the groups.

df['Group 1 Total by Count'] = df.groupby(['Group 0', 'Group 1'])['Count'].transform('sum')

Pandas中的分组总计

huangapple
  • 本文由 发表于 2023年2月14日 03:20:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75440351.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定