Skip to main content
cancel
Showing results for 
Search instead for 
Did you mean: 
rtrigor
Contributor
Contributor

Calculate column based on previous value of itself in previous row

Hello, I have this initial table:

TableA:

Row ValueA PCT
1 100.000 0
2 100.000 8%
3 100.000 5%
4 100.000 7%
5 100.000 6%
6 100.000 3%
7 100.000 5%

And I need to perform the following calculation for ValueB from ValueC:

Row ValueA PCT ValueB:
WHEN Row=1, ValueA
WHEN Row>1, (Pevious(ValueB) - Previous(ValueC))
ValueC = ValueB x PCT
1 100.000 0 100.000 -
2 100.000 8% 100.000 8.000,00
3 100.000 5% 92.000 4.600,00
4 100.000 7% 87.400 6.118,00
5 100.000 6% 81.282 4.876,92
6 100.000 3% 76.405 2.292,15
7 100.000 5% 74.113 3.705,65

Any clues?

I couldn't find a formula that worked using Previous() neither Peek().

Labels (2)
1 Reply
West69
Contributor II
Contributor II

I have a similar need for a vectorized solution. It would be nice if pandas provided version of apply() where the user's function is able to access one or more values from the previous row as part of its calculation or at least return a value that is then passed 'to itself' on the next iteration. Wouldn't this allow some efficiency gains compared to a for loop?

Fragomen Connect Portal