How to make my code nice as I am sure there must be neater solution. I have tried to solve it with pandas apply (but it does not use updated values but keeps the old values in memory). Shall I use some kind of function returning generator object e.g. iterrows? Maybe I could solve it somehow with cumsum or cumprod?
import pandas as pd
df = pd.DataFrame(data={'val':[0, 0.2, 0.1, 0.5, -0.6]})
prev = 100
val = []
for i in df['val'].tolist():
prev = prev * i + prev
val.append(prev)
df['val'] = val
I want to update column values according to the equation:
n = given value e.g. 100
v0 = 0, v1 = 0.2 etc.
y0 = n * v0 + n
y1 = y0 * v1 + y0
y2 = y1 * v2 + y1
etc.
You can use:
df['val'] = 100 * (df['val'] + 1).cumprod()
The reason this works is because your expression can be rewritten:
for i in df['val'].tolist():
prev *= (i + 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With