Reputation: 1327
I have a simple dataFrame
with regular samples:
dates = pd.date_range('20150101', periods=6)
df = pd.DataFrame([1,2,3,4,5,6], index=dates, columns=list('A'))
df.loc[:,'B'] = 0
df.iloc[0,1] =10
df
Out[119]:
A B
2015-01-01 1 10
2015-01-02 2 0
2015-01-03 3 0
2015-01-04 4 0
2015-01-05 5 0
2015-01-06 6 0
What I would like to do is using the rolling_sum
function in Pandas to create values in column B such that I get the following table:
A B
2015-01-01 1 11
2015-01-02 2 13
2015-01-03 3 16
2015-01-04 4 20
2015-01-05 5 25
2015-01-06 6 31
That is, B(i+1) = A(i+1) + B(i)
- note there is a special case at B(0) as there is an initial value of 10. I've tried using the following, but it gives the wrong answer:
df.B = pd.rolling_sum(df.A + df.B, 1)
Upvotes: 2
Views: 57
Reputation: 114976
Try expanding_sum
:
In [15]: df
Out[15]:
A B
2015-01-01 1 10
2015-01-02 2 0
2015-01-03 3 0
2015-01-04 4 0
2015-01-05 5 0
2015-01-06 6 0
In [16]: df.B = pd.expanding_sum(df.A) + df.B[0]
In [17]: df
Out[17]:
A B
2015-01-01 1 11
2015-01-02 2 13
2015-01-03 3 16
2015-01-04 4 20
2015-01-05 5 25
2015-01-06 6 31
Upvotes: 2