Reputation: 431
I have a pandas dataframe configured in the following structure:
date amount another_amount name
0 1/1 5 6 dave
1 2/1 3 4 dave
...
2 12/1 7 10 dave
How can I sum the previous row value for amount and another_amount until the last row will have the sum of the entire dataframe?
So for example the 2/1 row will have 8 (5+3) for amount and 10 (6+4) for another_amount, then the 3/1 row would have whatever that row contained plus the previous sum of 8 and 10 in their respective columns
I apologize if this a confusing question I will try to clarify as much as possible
Thanks!
Upvotes: 0
Views: 1165
Reputation: 61910
You could use cumsum:
df.iloc[:, 1:-1] = df.iloc[:, 1:-1].cumsum()
print(df)
Output
date amount another_amount name
0 1/1 5 6 dave
1 2/1 8 10 dave
2 12/1 15 20 dave
Or if you only want amount
and another_amount
:
df.loc[:, ['amount', 'another_amount']] = df.loc[:, ['amount', 'another_amount']].cumsum()
Upvotes: 2