Reputation: 329
Quick example:
Before:
In Out
1 5
10 0
2 3
After
In Out Value
1 5 -4
10 0 6
2 3 5
So the formula here is Value(rowx) = Value (rowx - 1) + In(rowx) - Out(rowx)
.
I started with adding a Value column where each cell is 0. I then have looked a shift() but that uses the value in the previous row from the start of the command/function. So it will always use 0 as the value for Value. Is there a way of doing this without using something like iterrows() or a for loop ?
Upvotes: 0
Views: 310
Reputation: 142641
It seems in your calculations you could first calculate In - Out
and later use cumsum()
import pandas as pd
data = {
'In': [1,10,2],
'Out': [5,0,3]
}
df = pd.DataFrame(data)
df['Value'] = df['In'] - df['Out']
df['Value'] = df['Value'].cumsum()
print(df)
or even shorter
df['Value'] = (df['In'] - df['Out']).cumsum()
Upvotes: 4