0

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()?

4
  • 1
    Are you against using df.shift or df.rolling? df.shift will do exactly what you are trying above but you're alluding to an unseen function you are attempting to calculate. Commented Nov 16, 2021 at 4:29
  • I don't think you can vectorize recursive functions like this. Have a look at stackoverflow.com/questions/38008390/… Commented Nov 16, 2021 at 11:23
  • @YoannQuenachdeQuivillic Yeah I had seen that answer. I was hoping to figure out a way to use apply/lambda, but perhaps you're right and I should just loop it. Commented Nov 16, 2021 at 13:04
  • @fam-woodpecker actual computation needs to take place. This example is just for the general structure, but I'm not looking to just move the index. Wasn't all that clear I guess. Edited Commented Nov 16, 2021 at 13:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.