Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to count percentage within group with categorical values?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading