Running sum in pandas (without loop)

Posted on

Question :

Running sum in pandas (without loop)

I’d like to build a running sum over a pandas dataframe. I have something like:

10/10/2012:  50,  0
10/11/2012: -10, 90
10/12/2012: 100, -5

And I would like to get:

10/10/2012:  50,  0
10/11/2012:  40, 90
10/12/2012: 140, 85

So every cell should be the sum of itself and all previous cells, how should I do this without using a loop.

Asked By: leo

||

Answer #1:

As @JonClements mentions, you can do this using the cumsum DataFrame method:

from pandas import DataFrame
df = DataFrame({0: {'10/10/2012': 50, '10/11/2012': -10, '10/12/2012': 100}, 1: {'10/10/2012': 0, '10/11/2012': 90, '10/12/2012': -5}})

In [3]: df
Out[3]: 
              0   1
10/10/2012   50   0
10/11/2012  -10  90
10/12/2012  100  -5

In [4]: df.cumsum()
Out[4]: 
              0   1
10/10/2012   50   0
10/11/2012   40  90
10/12/2012  140  85
Answered By: Andy Hayden

Leave a Reply

Your email address will not be published. Required fields are marked *