Pandas get frequency of item occurrences in a column as percentage

SANM2009 picture SANM2009 · May 28, 2018 · Viewed 62k times · Source

I want to get a percentage of a particular value in a df column. Say I have a df with (col1, col2 , col3, gender) gender column has values of M or F. I want to get the percentage of M and F values in the df.

I have tried this, which gives me the number M and F instances, but I want these as a percentage of the total number of values in the df.

df.groupby('gender').size()

Can someone help?

Answer

cs95 picture cs95 · May 28, 2018

Use value_counts with normalize=True:

df['gender'].value_counts(normalize=True) * 100