I have a dataframe df that looks something like that
print(df)
x outlier_flag
10 1
NaN 1
30 1
543 -1
50 1
I would like to substitute values flagged with outlier_flag==-1 with the interpolated values between row['A][i-1] and row['A][i+1], means I want to substitute the presented wrong value of 543 with 40.
What I could do is
df['x'] = df.apply(lambda row: np.nan if row['outlier_flag']==-1 else row['x'], axis=1)
df.interpolate(method='polynomial', order=3, inplace=True)
But I don't want to do this, because this would also interpolate nan values in df['x'] that are not marked with outlier_flag==-1 (see for that the second row)! Pure nan values, not marked by the flag, I want to keep as nan for a task later on.
So, is there a way to do the interpolation in place, even for a value like 543 that is not nan?
I tried doing
df['x'] = df.apply(lambda row: row['x'].interpolate(method='polynomial', order=3) if row['outlier_flag']==-1 else row['x'], axis=1)
But this throws an error, because only nan can be interpolated and 543 is int. Do you have a suggestion for me? Tnx