使用 groupby 选择行,汇总列并使用所有 groupby 元素的总和创建新列 [英] Selecting rows with groupby, summing columns and creating new column with the sum for all groupby elements

查看:70
本文介绍了使用 groupby 选择行,汇总列并使用所有 groupby 元素的总和创建新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个数据框:

nome 代码tipo 分数亚历山大 AAA Frads 4000亚历山大 AAA 会员 10000亚历山大 AAA 会员 20000布鲁诺 BBB 丹斯 10000布鲁诺 BBB Grap 4000

我用 transform('sum') 尝试了 groupby 但是它得到了错误的结果.

df['score'].loc[df['tipo'] == "Memb"]=df[['nome','code','score']].groupby(['nome','code'])['score'].transform('sum')

我错过了什么?

解决方案

为了提高性能,可以通过 Series.mask 然后使用 GroupBy.transformsum :

df['Memb_sum'] = (df.assign(score=df['score'].mask(df['tipo'] != 'Memb', 0)).groupby(['nome','code'])['score'].transform('sum'))打印 (df)nome 代码 tipo 分数 Memb_sum0 亚历山大 AAA 弗拉兹 4000 300001 亚历山大 AAA 会员 10000 300002 亚历山大 AAA 会员 20000 300003 布鲁诺 BBB 丹斯 10000 04 布鲁诺 BBB Grap 4000 0

详情:

print (df.assign(score=df['score'].mask(df['tipo'] != 'Memb', 0)))名称代码tipo分数0 亚历山大 AAA 弗拉兹 01 亚历山大 AAA 会员 100002 亚历山大 AAA 会员 200003 布鲁诺 BBB 丹斯 04 布鲁诺 BBB Grap 0

I have this dataframe:

nome       code  tipo   score
Alexandre   AAA  Frads  4000
Alexandre   AAA  Memb   10000
Alexandre   AAA  Memb   20000
Bruno       BBB  Dans   10000
Bruno       BBB  Grap   4000

Values available in this Google Sheets

I need to create a new column summing the rows with same nome and code where tipo = 'Memb', in a way that it looks like this:

I tried groupby with transform('sum') however it is getting me the wrong result.

df['score'].loc[df['tipo'] == "Memb"]=df[['nome','code','score']].groupby(['nome','code'])['score'].transform('sum')

What am I missing?

解决方案

For improve performance is possible replace score to 0 values by Series.mask and then use GroupBy.transform with sum:

df['Memb_sum']  = (df.assign(score=df['score'].mask(df['tipo'] != 'Memb', 0))
                     .groupby(['nome','code'])['score']
                     .transform('sum'))
print (df)
        nome code   tipo  score  Memb_sum
0  Alexandre  AAA  Frads   4000     30000
1  Alexandre  AAA   Memb  10000     30000
2  Alexandre  AAA   Memb  20000     30000
3      Bruno  BBB   Dans  10000         0
4      Bruno  BBB   Grap   4000         0

Details:

print (df.assign(score=df['score'].mask(df['tipo'] != 'Memb', 0)))

        nome code   tipo  score
0  Alexandre  AAA  Frads      0
1  Alexandre  AAA   Memb  10000
2  Alexandre  AAA   Memb  20000
3      Bruno  BBB   Dans      0
4      Bruno  BBB   Grap      0   

这篇关于使用 groupby 选择行,汇总列并使用所有 groupby 元素的总和创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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