0

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
Konstantin F
  • 180
  • 1
  • 15
  • Can you show an example for `df` before you do any calculations? It would be easier if it were provided in a format that can be copied and pasted directly (as opposed to having to remove the Markdown table syntax by hand). – Steele Farnsworth Nov 20 '21 at 17:32

1 Answers1

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

Output:

>>> df
   year  value
0  1960      5
1  1962     17
2  2000      4
3  2020     19
  • 1
    Thank you user17242583, I just found a similar solution here: https://stackoverflow.com/questions/39922986/pandas-group-by-and-sum – Konstantin F Nov 20 '21 at 17:42