Python 熊猫数据帧中的groupby和百分位计算
我有一个这样的数据帧Python 熊猫数据帧中的groupby和百分位计算,python,pandas,Python,Pandas,我有一个这样的数据帧 name event spending abc A 500 abc B 300 abc C 200 xyz A 2000 xyz D 1000 所以我需要一个groupby名称和事件,并计算相应的百分比…所以输出应该是 name event spending_percentile abc A 50% abc B 30% abc C 20%
name event spending
abc A 500
abc B 300
abc C 200
xyz A 2000
xyz D 1000
所以我需要一个groupby名称和事件,并计算相应的百分比…所以输出应该是
name event spending_percentile
abc A 50%
abc B 30%
abc C 20%
xyz A 66.67%
xyz D 33.33%
请指导如何在熊猫数据框中执行此操作。您似乎需要:
相关的和可能的欺骗:@EdChum:对不起,没有正确地使用谷歌(当时很匆忙)…谢谢,那个链接很有用。帮了大忙..谢谢@jezrael
df['spending_percentile'] = df['spending'].div(df.groupby('name')['spending']
.transform(sum)).mul(100)
print (df)
name event spending spending_percentile
0 abc A 500 50.000000
1 abc B 300 30.000000
2 abc C 200 20.000000
3 xyz A 2000 66.666667
4 xyz D 1000 33.333333