Pandas missing values : fill with the closest non NaN value Pandas missing values : fill with the closest non NaN value python python

Pandas missing values : fill with the closest non NaN value


You could use Series.interpolate with method='nearest':

In [11]: s = pd.Series([0, 1, np.nan, np.nan, np.nan, np.nan, 3])In [12]: s.interpolate(method='nearest')Out[12]: 0    0.01    1.02    1.03    1.04    3.05    3.06    3.0dtype: float64In [13]: s = pd.Series([0, 1, np.nan, np.nan, 2, np.nan, np.nan, 3])In [14]: s.interpolate(method='nearest')Out[14]: 0    0.01    1.02    1.03    2.04    2.05    2.06    3.07    3.0dtype: float64