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 get sum() for each year and return years and sum of those years in Pandas

I am using the below code:

df.groupby(['year','value']).sum().groupby(['year','value']).count()

And it produces the following table:

year  value
1960  5
1962  6
      4
      7
2000  4
2020  7
      3
      9

My question is how to get the sum of value for each year without using a for loop. If it’s possible, I presume that cumsum() will be the best solution.

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

Expected result:

year  value
1960  5
1962  17
2000  4
2020  19

>Solution :

df = df.groupby('year').sum().reset_index()

Output:

>>> df
   year  value
0  1960      5
1  1962     17
2  2000      4
3  2020     19
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