繁体   English   中英

熊猫数据框中的分组比和百分位数计算

[英]groupby and percentile calculation in pandas dataframe

我有一个这样的数据框

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%

请在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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM