"groupby"返回基于特定条件的发生百分比



基于类似于

的数据框架
Strategy    Profit
AA          100 
AA           50
AA          -50
BB          -20
BB          180
CC          -20
DD           20

我想按"策略"分组。并拥有时间和利润的百分比;

我目前做这个相当质朴(循环遍历策略),但我需要一个更直接的方法,因为有太多的记录,有太多不同的"策略"。

df.groupby("Strategy")["Profit"].count() # total of ocurrences per "strategy"
df[df["Profit"] > 0].groupby("Strategy")["Profit"].count() # total of positive results

预期结果:

Strategy   Assertiveiness %
AA           66,66 
BB              50
CC               0
DD             100

感谢你的帮助!

这只是groupby+mean

df["Profit"].gt(0).groupby(df["Strategy"]).mean().mul(100)
Strategy
AA     66.666667
BB     50.000000
CC      0.000000
DD    100.000000
Name: Profit, dtype: float64

最新更新