Home > Back-end >  How to count percentage within group with categorical values?
How to count percentage within group with categorical values?

Time:07-11

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

CodePudding user response:

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

  • Related