基于类似于
的数据框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
感谢您的帮助!
答案 0 :(得分:2)
这只是 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