How to further break down a column based on another column after grouping it?

Question:

I want to find the number of suicides that occurred from year 1985-2016. Which i did easily
by

df.groupby('year').suicides_no.sum()

Now i want to break down the total number of suicides happened per year further into male and female.
The column name is ‘sex’ which contains two values – male , female.

Asked By: Divyajeet Singh

||

Answers:

Simply add a further group (long format):

df.groupby(['year', 'sex'])['suicides_no'].sum()

Or use a crosstab (wide format):

pd.crosstab(df['year'], df['sex'], values=df['suicides_no'], aggfunc='sum')
Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.