vuvu
vuvu

Reputation: 268

fill cells containing nan with average of values immediately before and after

I have a question very similar to Fill cell containing NaN with average of value before and after the only addition being that several entries in a row might be NaNs, and then the replacement should be done with averages too, or better with linearly adjusted averages, for example: [1, nan, nan, 4, ...] should become [1, 2, 3, 4, ...] and [8, nan, nan, 2, ...] should become [8, 6, 4, 2, ...] etc. Is this still possible?

Upvotes: 1

Views: 53

Answers (1)

Scott Boston
Scott Boston

Reputation: 153460

Use interpolate:

df=pd.DataFrame({'A':[1,np.nan, np.nan, 4],'B':[8,np.nan,np.nan,2]})


     A    B
0  1.0  8.0
1  NaN  NaN
2  NaN  NaN
3  4.0  2.0


df.interpolate()

Output:

     A    B
0  1.0  8.0
1  2.0  6.0
2  3.0  4.0
3  4.0  2.0

Upvotes: 2

Related Questions