我有一个大数据集(> 200k),我正在尝试用一个值替换零序列。具有超过 2 个零的零序列是一个伪影,应该通过将其设置为 np.NAN 来移除。
我已阅读 Searching a sequence in a NumPy array但它并不完全符合我的要求,因为我没有静态模式。
np.array([0, 1.0, 0, 0, -6.0, 13.0, 0, 0, 0, 1.0, 16.0, 0, 0, 0, 0, 1.0, 1.0, 1.0, 1.0])
# should be converted to this
np.array([0, 1.0, 0, 0, -6.0, 13.0, NaN, NaN, NaN, 1.0, 16.0, NaN, NaN, NaN, NaN, 1.0, 1.0, 1.0, 1.0])
如果您需要更多信息,请告诉我。 提前致谢!
结果:
感谢您的回答,这是我(非专业)在 288240 点上运行的测试结果
divakar took 0.016000ms to replace 87912 points
desiato took 0.076000ms to replace 87912 points
polarise took 0.102000ms to replace 87912 points
因为@Divakar 的解决方案是最短和最快的,所以我接受他的解决方案。
最佳答案
嗯,这基本上是一个 binary closing operation
对收窄差距有阈值要求。这是基于它的实现 -
# Pad with ones so as to make binary closing work around the boundaries too
a_extm = np.hstack((True,a!=0,True))
# Perform binary closing and look for the ones that have not changed indiicating
# the gaps in those cases were above the threshold requirement for closing
mask = a_extm == binary_closing(a_extm,structure=np.ones(3))
# Out of those avoid the 1s from the original array and set rest as NaNs
out = np.where(~a_extm[1:-1] & mask[1:-1],np.nan,a)
一种避免在早期方法中根据需要追加边界元素的方法是这样的——
# Create binary closed mask
mask = ~binary_closing(a!=0,structure=np.ones(3))
idx = np.where(a)[0]
mask[:idx[0]] = idx[0]>=3
mask[idx[-1]+1:] = a.size - idx[-1] -1 >=3
# Use the mask to set NaNs in a
out = np.where(mask,np.nan,a)
关于python - 用其他值替换零序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38584956/