Find the ratio of rows by column category… here is a solution to the problem.
Find the ratio of rows by column category
I have the following Python pandas dataframe df:
Week | Category | Executed
Wk1 A 0
Wk1 B 0
Wk1 C 1
Wk2 D 1
Wk2 E 0
I want to calculate the rate of how many categories are executed each week.
The final destination data frame df2:
Week | Exec_Ratio
Wk1 0.3333
Wk2 0.5
At week 1, 1 of the 3 categories – > 1/
3 = 0.333 was performed, and at week 2, 1 of the 2 categories – > 1/2 = 0.5 was performed
Solution
Inferior to the comments of @A-Za-z for this particular purpose … However, more universal.
df.groupby('Week'). Executed.agg(dict(Sum='sum', Count='count')).eval('Sum / Count')
Week
Wk1 0.333333
Wk2 0.500000
dtype: float64