python - 如何用紧邻屏蔽值的平均值替换 numpy 数组中的屏蔽值

标签 python arrays numpy masking

将数组中的屏蔽值替换为它们旁边最接近的未屏蔽值的平均值的最有效 numpy 方法是什么?

例如:

a = np.array([2,6,4,8])
b = np.ma.masked_where(a>5,a)
print b

masked_array(data = [2 -- 4 --],
         mask = [False  True False  True],
   fill_value = 999999)

我希望将 b 中的掩码值替换为紧邻它们的平均值。边界可以重复最接近的未屏蔽值。因此,在此示例中,b 将如下所示:

b = [2,3,4,4]

提出这个问题的主要原因是看看是否可以在不使用迭代器的情况下有效地完成此操作。

最佳答案

你可以使用np.interpnp.where

import numpy as np

a = np.array([2,6,4,8])
mymask = a>5
b = np.ma.masked_where(mymask,a)

print b
# [2 -- 4 --]

c = np.interp(np.where(mymask)[0],np.where(~mymask)[0],b[np.where(~mymask)[0]])
b[np.where(mymask)[0]] = c

print b
# [2 3 4 4]

关于python - 如何用紧邻屏蔽值的平均值替换 numpy 数组中的屏蔽值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32450900/

相关文章:

python - RSS feedparser 到 MySQL 数据库未填充

python - pandas系列的for循环性能

arrays - 通用异步数组的 enumerate() 方法

python - 使用 pandas 在 matplotlib 中绘图

python - 根据距椭圆中心的距离计算权重

python 使用 if 语句编辑文件

javascript - 使用 jQuery 设置复选框

javascript - 在javascript block 中遍历twig数组

python - cv2.COLOR_BGR2Lab 不工作,但 cv2.COLOR_BGR2GRAY 正在工作

python - 内置范围或 numpy.arange : which is more efficient?