How to count percentage within group with categorical values?

Viewed 40

I have a dataframe:

id   value_type
1       b
1       a
1       a
2       a
3       a
3       b

I want to calculate percent of each value_type with each id group.so desired result is:

id   value_type       perc
1       b             0.33
1       a             0.66
2       a             1
3       a             0.5
3       b             0.5

How could I do that? I tried groupby().size() but it counts, but i need percentages

2 Answers

Check below code:

import pandas as pd

df = pd.DataFrame({'col1':[1,1,1,2,3,3],'col2':['b','a','a','a','a','b']})

df['perc'] = df.groupby(['col1','col2'])['col2'].transform('count')/df.groupby('col1')['col2'].transform('count')

df.round(2).drop_duplicates()

Output:

enter image description here

you also can do something like this:

res = df.groupby('id').value_counts(normalize=True).reset_index(name='perc')

print(res)
'''
   id value_type      perc
0   1          a  0.666667
1   1          b  0.333333
2   2          a  1.000000
3   3          a  0.500000
4   3          b  0.500000
Related