Pandas group by column find percentage of count in each group

Viewed 3049
    age    section   count
0   13-17   a         160
1   25-34   c         128
2   13-17   d         128
3   25-34   a         120
4   35-44   b         120
5   35-44   a         120
6   25-34   b         112

How can I calculate percentage of count in each group?

Ex output:

    age    section   count  perc
0   13-17   a         160   55.5
1   25-34   c         128   35.5
2   13-17   d         128   44.4
3   25-34   a         120   33.3
4   35-44   b         120   50
5   35-44   a         120   50
6   25-34   b         112   31.1

So for example for age 13-17 perc for the above example is = 160/288 and 128/288.

What I could manage is this query:

df.groupby(['age'])['count'].agg('mean') 

But this doesn't give what I am looking for. Any help?

1 Answers

You can calculate percentage for each age/count using lambda

df['perc'] = df.groupby('age')['count'].apply(lambda x: x*100/x.sum())


    age section count   perc
0   13-17   a   160     55.555556
1   25-34   c   128     35.555556
2   13-17   d   128     44.444444
3   25-34   a   120     33.333333
4   35-44   b   120     50.000000
5   35-44   a   120     50.000000
6   25-34   b   112     31.111111

If you want to round the percentage values,

df['perc'] = df.groupby('age')['count'].apply(lambda x: np.round(x*100/x.sum(), 2))
Related