Hi Assuming I have a df
x=[.12,.02,.05,.04]
y=[1,1,1,1]
df=pd.DataFrame(dict(x=x,y=y))
but I want to change values under column 'y' in way that first row is 100, 2nd row is 102 (i.e. 100*.02) third row is 107.1 (102*1.05) and so on.
How do I do that? (I think it should be done using shift function?)
I believe you need cumprod()
. It requiered a bit of a hardcoding for the first number, afterwards it seems fine.
import pandas as pd
import numpy as np
x=[.12,.02,.05,.04]
y=[1,1,1,1]
df=pd.DataFrame(dict(x=x,y=y))
df['x'] = df['x'] + 1 #Add 1 to make the cumprod() easier
df['y'].loc[0] = 100 #Force the first value to be 100
df['y'].loc[1:] = df['x'].loc[1:].cumprod() * df['y']
df['x'] = df['x'] - 1 #Substract 1 to keep original values
Output:
x y
0 0.12 100.00000
1 0.02 1.02000
2 0.05 1.07100
3 0.04 1.11384