Home > Enterprise >  Calculating a column's values based on previous row and a conditional
Calculating a column's values based on previous row and a conditional

Time:07-10

I would like to use the following example pseudocode/calculation on a dataframe, where the calculation needs to conditionally use a previous row value. I think I could do this using apply()but is there a fast vectorised solution?

df['result'] = 1 # init/base value
If df['data'] > 10: df['result'] = df['data'] * 2 - df['result'].shift(1)
else df['result'] = df['result'].shift(1)

Thanks!

CodePudding user response:

You can use np.where

df['result'] = np.where(df['data'] > 10, df['data'] * 2 - df['result'].shift(1), df['result'].shift(1))
  • Related