Is there a way to vectorize this? Currently I an looping through the dataframe as column values depend on previous values of other columns.
Column F depends on previous version of G
Column G also depends current value of F which as stated previously depends on previous value of G
import pandas as pd
data = [[1,2131000,2131000,77.13],
[1,269000,2400000,79.25],
[1,1340000,3740000,81],
[1,268000,4008000,83.75],
[-1,1073000,2935000,85],
[1,269000,3204000,75]]
df = pd.DataFrame(data,columns=['Flag','Q','Cumsum Q','P'])
df['P*Q'] = df['P']*df['Q']
df.loc[0,'Adj P*Q'] = df.loc[0, 'P*Q']
df.loc[0,'Adj P'] = df.loc[0, 'P']
for index, row in df.iloc[1:,].iterrows():
df.loc[index,'Adj P*Q'] = np.where(df.loc[index,'Flag'] == 1, df.loc[index-1,'Adj P*Q'] + df.loc[index,'P*Q'] * df.loc[index,'Flag'], df.loc[index-1,'Adj P'] * df.loc[index,'Cumsum Q'])
df.loc[index,'Adj P'] = np.where(df.loc[index,'Flag'] == 1, df.loc[index,'Adj P*Q'] / df.loc[index,'Cumsum Q'], df.loc[index-1,'Adj P'])