Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python pandas update column values related to previous updated row during iteration over it

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. 
like image 900
naivepredictor Avatar asked Nov 18 '25 10:11

naivepredictor


1 Answers

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)
like image 188
jpp Avatar answered Nov 20 '25 23:11

jpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!