I am new to python so still learning. Forgive me if this question is ignorant but I am having trouble with applying a function to a column in a data frame that already has data. Basically, what I am trying to do is create a function that reads each row in column x of the df and based on whether it equals 0 and the row above it equals 1 or -1 will do a calculation and apply this to column a. Otherwise if it doesn’t meet any of these conditions, I just want it to leave column a be and not adjust the number that was previously there. x, y, z, a are all columns in a dataframe.
def goFlat(x, y, z, a):
if (x == 0) & (x.shift(1) == 1):
return y*z*-1
elif (x == 0) & (x.shift(1) == -1):
return y*z*1
else:
a
df1['a'] = goFlat(df1['x'], df1['y'], df1['z'], df1['a'])
Again, I’m sure there is a better way to go upon this so if anyone has any suggestions, they would be much appreciated. TIA