在 numpy 数组中用最近的邻居填充 nan

Fill nan with nearest neighbor in numpy array

我得到了这个带有缺失值的 2D numpy 数组。是否有一种简单(且相当快)的方法用最接近的(最好是欧氏距离,但曼哈顿也可以)非南值填充南值?我在 numpy 或 scipy…

中找不到这样的函数

使用scipy.interpolate.NearestNDInterpolator.

例如:

from scipy.interpolate import NearestNDInterpolator
data = ... # shape (w, h)
mask = np.where(~np.isnan(data))
interp = NearestNDInterpolator(np.transpose(mask), data[mask])
filled_data = interp(*np.indices(data.shape))

实际展示(此处以黑色作为遮罩,image_defect 来自 from here):

data = image_defect
mask = np.where(~(data == 0))
interp = NearestNDInterpolator(np.transpose(mask), data[mask])
image_result = interp(*np.indices(data.shape))

然后,使用 scipy 中的绘图代码: