I want to replace negative numbers, NaNs and 0s with mean of next and previous positive number of same column.
Original dataframe
a c
0 1 1
1 2 2
2 0 5
3 -3 NaN
4 -1 5
5 3 3
Expected output dataframe is
a c
0 1 1
1 2 2
2 2.5 5 #In Col a --> Mean of 2 and 3 is 2.5 hence 0 replaced by 2.5
3 2.75 5 #In Col a --> Mean of 2.5 and 3 is 2.75 hence negative no. replaced by 2.75
4 2.875 5 #In Col a --> Mean of 2.75 and 3 is 2.875 hence negative no. replaced by 2.875
5 3 3
I tried another strategy to deal with negative no. Nan and 0 is replacing it with mean of previous 3 values
m = df['a'] < 1
new = (df.loc[~m, 'a'].astype(float)
.rolling(2, min_periods=1).mean()
.reindex(df.index, method='ffill'))
df['a'].mask(m, new)
which results in
0 1.0
1 2.0
2 1.5
3 1.5
4 1.5
5 2.0
Name: a, dtype: float64
However I'm struggling to implement the new strategy (asked).