Pandas Calculate percentage by column values

Viewed 527

The dataframe is like below

id age
a 30-40
b 30-40
c 30-40
d 40-50
e 40-50

The count of '30-40' is 3, the count of '40-50' is 2. The output I want is just value, I don't care about the format. Here is the output

age percentage
30-40 60.00%
40-50 40.00%
1 Answers

Use Series.value_counts with normalize=True, then multiple by 100 and change format to DataFrame:

df1 = (df['age'].value_counts(normalize=True)
                .mul(100)
                .rename_axis('age')
                .reset_index(name='percentage'))
print (df1)
     age  percentage
0  30-40        60.0
1  40-50        40.0
Related