我有一个一维 NumPy 数组,其中包含一些“坏”值。我想剔除它们。
每个坏值的邻居只是“顽皮”,但我也想剔除它们。
对不良值的可靠测试是询问:
arr<0.1
但是,(我能想到的)对于顽皮值的唯一可靠测试是它与坏值相邻。
我使用以下策略来消除不良和顽皮的值(value)观:
import numpy as np
c = np.random.random(100) #Construct test data
who = np.where(c<0.1)[0] #Reliable test for bad values
c[who] = 0 #Zero bad values
#Add and subtract from the indices of the bad values to cull
#their neighbours
wht = who-1; wht = wht[np.logical_and(0<wht,wht<len(c))]; c[wht]=0
wht = who+1; wht = wht[np.logical_and(0<wht,wht<len(c))]; c[wht]=0
wht = who+2; wht = wht[np.logical_and(0<wht,wht<len(c))]; c[wht]=0
wht = who-2; wht = wht[np.logical_and(0<wht,wht<len(c))]; c[wht]=0
不幸的是,上述速度相当慢。
是否有更快的方法来执行此操作或类似的操作?
最佳答案
针对邻居的通用窗口长度的一种可扩展解决方案是 binary-dilate
阈值比较的掩码,然后使用该掩码设置零 -
from scipy.ndimage.morphology import binary_dilation
W = 2 # window length of neighbors
thresh = 0.1
mask = c < thresh
kernel = np.ones(2*W+1)
mask_extended = binary_dilation(mask, kernel)
c[mask_extended] = 0
关于python - 消除一维阵列中的 Blob / Blob ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50399189/