42piratas
42piratas

Reputation: 595

"groupby" returning the percent of occurrences based on a certain condition

Based on a dataframe similar to

Strategy    Profit
AA          100 
AA           50
AA          -50
BB          -20
BB          180
CC          -20
DD           20

I would like to groupby "Strategy" and have the percent of time "Profit" is positive (i.e. bigger than zero - the condition).

I currently do this quite rustically (looping through the strategies), but I need a more straightforward approach because there are too many records, with too many different "Strategies".

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

Expected result:

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

Appreciate the help!

Upvotes: 1

Views: 50

Answers (1)

user3483203
user3483203

Reputation: 51165

This is just 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

Upvotes: 2

Related Questions