Q: Pandas : Replace NaNs with mean of 'n' nearest non-empty values in column Suppose I have the following dataframe.
     A      B
0   NaN     12
1   NaN    NaN
2    24    NaN
3   NaN    NaN
4   NaN     13
5   NaN     11
6   NaN     13
7    18    NaN
8    19    NaN
9    17    NaN

In column 'A', the missing values need to replaced with the mean of say 3 nearest non empty values in a sequence if they exist. For example the NaN at index 5 has 18 as its nearest non empty value and after 18, the next two values are also non empty. Therefore the NaN at index 5 is replaced with (18+19+17)/3.
The NaN at index 4 has 24 as its nearest non empty value but the two values prior to 24 are non empty. Therefore the NaN at index 4 is not replaced with any value.
Similarly it needs to be done with the rest of the columns. Does anyone know a vectorized way of doing this? 
Thanks!

A: I believe you need combine rolling with mean with another rolling from back, then use DataFrame.interpolate for replace nearest NaNs by means with forward filling for last groups of NaNs and backfilling for first groups of NaNs for helper DataFrame c, which is used for replace missing values of original DataFrame:
a = df.rolling(3).mean()
b = df.iloc[::-1].rolling(3).mean()

c = a.fillna(b).fillna(df).interpolate(method='nearest').ffill().bfill()
print (c)
      A          B
0  24.0  12.000000
1  24.0  12.000000
2  24.0  12.000000
3  24.0  12.333333
4  24.0  12.333333
5  18.0  11.000000
6  18.0  12.333333
7  18.0  12.333333
8  19.0  12.333333
9  18.0  12.333333

df = df.fillna(c)
print (df)
      A          B
0  24.0  12.000000
1  24.0  12.000000
2  24.0  12.000000
3  24.0  12.333333
4  24.0  13.000000
5  18.0  11.000000
6  18.0  13.000000
7  18.0  12.333333
8  19.0  12.333333
9  17.0  12.333333

