0

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.

1 Answers1

1

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')
mozway
  • 194,879
  • 13
  • 39
  • 75
  • 1
    I can't believe how simply the answer was. Thank you bro. I totally forgot that you can add multiple columns in groupby() function. I was adding the sex column with the suicides_no column insteading of adding it along with the year in the groupby(). – Divyajeet Singh Mar 24 '23 at 11:17