我有一个包含一些“坏”值的一维NumPy数组。我想把它们剔除。
每个坏值的邻居都是“淘气的”,但我也想剔除它们。
对于不好的值,一个可靠的测试是问:
arr<0.1然而,对于一个淘气值,唯一可靠的(我能想到的)测试就是它靠近一个坏的值。
我正在使用以下策略来消除不好的和不好的值:
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不幸的是,上述过程相当缓慢。
有没有更快的方法来执行这个或类似的操作?
发布于 2018-05-18 03:48:05
对于邻居的通用窗口长度,一种可扩展的解决方案是对阈值比较的掩码进行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] = 0https://stackoverflow.com/questions/50399189
复制相似问题