To return a percentage result from a boolean (True/False) Column using groupby in Python Pandas

group-by, pandas, python

Solution

# you can use a apply function to do your own calculations.

widgets.groupby('Colour')['Pass'].apply(lambda x: np.sum(x)/len(x))
Out[289]: 
Colour
blue      1.000000
green     1.000000
purple    1.000000
red       0.888889
Name: Pass, dtype: float64

Problem

I would like to return a percentage (Pass) rate for some widgets (coloured either red, blue, green or purple). I have added a column (Pass) to test if the widgets are in tolerance (13 to 14 inclusive), now using the groupby function I would like to return what percentage have passed by colour, I just don't know how to add this to my groupby function. My code is: ``` #Create new series called Pass to test if in tolerance widgets['Pass'] = widgets.Vals.between(13, 14, inclusive=True) print(widgets.head(20)) #Group by Colours - blue, green, purple, red #Give results - count, pass(%), mean, var widgets = widgets.groupby('Colour').Vals.agg(['count', 'mean', 'var']) print(widgets) ``` The result is: ``` Vals Colour Pass 0 13.166671 red True 1 13.844101 red True 2 13.667672 purple True 3 13.457526 red True 4 13.512347 red True 5 13.421277 green True 6 13.692874 red True 7 13.768719 red True 8 13.489158 blue True 9 13.487612 blue True 10 13.611823 purple True 11 14.193408 red False 12 13.344894 purple True 13 13.585790 purple True 14 13.274137 blue True 15 13.447983 red True 16 13.766603 blue True 17 13.711676 purple True 18 13.514098 blue True 19 13.326753 red True count mean var Colour blue 11225 13.500443 0.064099 green 11014 13.504158 0.063477 purple 11143 13.496960 0.064687 red 16618 13.501518 0.062595 ```

Original source