I am currently working with a dataframe where calculations must be done sequentially (i.e the calculation for each row requires the calculation from the previous row). As such vectorization is simply not possible (as df.shift is not viable) and therefore I must iterate.
I have written a function which does these calculations successfully using a for loop and df.itertuples(). However, to access the newly calculated value from the previous row I am using df.at[index-1, "Column Name"]. And although this works, due to the vast number of columns on which I must conduct calculations, accessing so many values by index has bottlenecked my code.
Here is a simplified example of what my code looks like:
(these are arbitrary calculations but I hope they get my thought process across)
df=pd.DataFrame({"Column 0":[1,2,3,4,5,6,7,8,9,10]})
df["Column1"]=np.nan
df["Column2"]=np.nan
df["Column3"]=np.nan
for row in df.itertuples():
index=row.Index
if index==0:
df.at[index, "Column1"]=0
df.at[index, "Column2"]=1
df.at[index, "Column3"]=10
else:
df.at[index, "Column1"]=df.at[index-1, "Column2"]+df.at[index-1, "Column3"]
df.at[index, "Column2"]=df.at[index, "Column1"]+df.at[index-1, "Column3"]
df.at[index, "Column3"]=df.at[index, "Column2"]*row.Column0 + df.at[index-1, "Column1"]
So my question; is it is possible to avoid having to access these newly calculated values by index and index-1?