向Pandas中的数据框添加组总计的最佳方法 [英] Best Way to add group totals to a dataframe in Pandas

查看:55
本文介绍了向Pandas中的数据框添加组总计的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的任务,我想知道是否有更好/更有效的方法.我有一个看起来像这样的数据框:

I have a simple task that I'm wondering if there is a better / more efficient way to do. I have a dataframe that looks like this:

  Group  Score  Count
0     A      5    100
1     A      1     50
2     A      3      5
3     B      1     40
4     B      2     20
5     B      1     60

我想添加一列,其中包含组总计数的值:

And I want to add a column that holds the value of the group total count:

  Group  Score  Count  TotalCount
0     A      5    100         155
1     A      1     50         155
2     A      3      5         155
3     B      1     40         120
4     B      2     20         120
5     B      1     60         120

我这样做的方式是:

Grouped=df.groupby('Group')['Count'].sum().reset_index()
Grouped=Grouped.rename(columns={'Count':'TotalCount'})

df=pd.merge(df, Grouped, on='Group', how='left')

是否有更好/更干净的方法将这些值直接添加到数据框中?

Is there a better / cleaner way to add these values directly to the dataframe?

感谢您的帮助.

推荐答案

df['TotalCount'] = df.groupby('Group')['Count'].transform('sum')

讨论了其他一些选项 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆