gpt4 book ai didi

python - pandas 数据框中的 groupby 和百分位计算

转载 作者:行者123 更新时间:2023-12-01 03:00:33 25 4
gpt4 key购买 nike

我有一个像这样的数据框

name event  spending
abc A 500
abc B 300
abc C 200
xyz A 2000
xyz D 1000

所以我需要一个分组名称和事件并计算相应的百分位数...所以输出应该像

name  event  spending_percentile
abc A 50%
abc B 30%
abc C 20%
xyz A 66.67%
xyz D 33.33%

请指导如何在 pandas Dataframe 中执行此操作。

最佳答案

看来你需要transform :

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

关于python - pandas 数据框中的 groupby 和百分位计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43887445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com