Let's say I have the following dataset
A B
0 1 1
1 NaN 3
2 5 2
3 7 4
4 NaN 3
5 3 3
I want to fill NaNs with some function, for example mean, of values A of nearest neighbors by B by given threshold. For example, if threshold is 1, then
for object 0 neighbors are object 2 (because 2 - 1 <= 1)
for object 1 neighbors are objects 2, 3, 4, 5
and so on so the result would be
A B
0 1 1
1 5 3 # 5 = (5 + 7 + 3) / 3
2 5 2
3 7 4
4 5 3 # 5 = (5 + 7 + 3) / 3
5 3 3
If NaNs are faced in computations, they are neglected. How can I do that?