Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading