Anthony W
Anthony W

Reputation: 1327

Pandas cumsum with initial value

So given the following single column data frame:

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

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

I would like to create a cumulative sum for a given column, but give the accumulator an initial value. So for the dataframe above and with an initial value of 100, this would look like:

              0  1 
10/10/2012   50  150 
10/11/2012  -10  140
10/12/2012  100  240

Any help, much appreciated.

Upvotes: 3

Views: 3528

Answers (1)

Leb
Leb

Reputation: 15953

from pandas import DataFrame

df = DataFrame({0: {'10/10/2012': 50, '10/11/2012': -10, '10/12/2012': 100}})

print(df)

That will give you the following result

              0
10/10/2012   50
10/11/2012  -10
10/12/2012  100

df[1] = df[0].cumsum()+100

print(df)

After creating a new column df[1], take the cumulative sum of df[0] then add 100 to it.

              0    1
10/10/2012   50  150
10/11/2012  -10  140
10/12/2012  100  240

Upvotes: 5

Related Questions