I'm trying to accomplish the following:
- Compute a column within a dataframe for which a cell's value depends on the previous one
- use apply & lambda function to contain the logic/formula
I'm doing the following (I'll manage indexes better than with a try/except, but for testing):
def func(row, df_foo):
i = row.name
try:
new_row = df_foo["bar"].iloc[i-1] + row.name # or wathever computation
except:
new_row = 1
return new_row
I'm calling it this way:
df_foo["bar"] = df_p1.apply(lambda row:func(row, df_foo), axis=1)
However, when I access df_foo.bar within func(), the previous value hasn't been calculated. I'm guessing the updated value isn't accessible fron within the lambda? Or it's updated only after the lambda evaluates for all values?
Is there a way that I could keep this general structure, while accessing update values for df_foo["bar"].iloc[i-1]
within func()
?