Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (50.2k points)

I was experimenting with the kaggle.com Titanic data set (data on every person on the Titanic) and came up with a gender breakdown like this:

gender = df.sex.value_counts()

gender

male   577

female 314 

I would like to find out the percentage of each gender on the Titanic.

My approach is slightly less than ideal:

from __future__ import division

pcts = gender / gender.sum()

pcts

male      0.647587

female    0.352413

Is there a better (more idiomatic) way?

Thanks!

1 Answer

0 votes
by (108k points)

This function is implemented in pandas, You just have to type:

df.sex.value_counts(normalize=True)

which gives exactly the desired output.

As you know that the value_counts() eliminates NA values, so numbers might not add up to 1. Refer the following link for more information regarding the same: http://pandas-docs.github.io/pandas-docs-travis/reference/api/pandas.Series.value_counts.html

Browse Categories

...