【问题标题】:Fill nan with nearest neighbor in numpy array用numpy数组中的最近邻居填充nan
【发布时间】:2021-09-12 18:56:34
【问题描述】:

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

【问题讨论】:

  • 并不是说这不是stackoverflow.com/questions/9537543/…的重复,那个问题的标题只是误导
  • 用周围像素的平均值填充这个点就足够了吗?
  • 如果有多个不同的值相同的距离?
  • @Conic 周围的像素也可能是 NaN。但是对于我的应用程序,平均值也可以
  • @Scott Hunter 那么这些都可以

标签: python numpy nan


【解决方案1】:

使用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 中的绘图代码:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 2012-03-21
    • 2021-10-04
    • 1970-01-01
    • 2017-05-02
    相关资源
    最近更新 更多