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.

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

Leave a Reply