python - 用其他值替换零序列

标签 python python-2.7 numpy

我有一个大数据集(> 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/

相关文章:

python - 在Python中计算累积密度函数的导数

python - 单元测试中的设置部分似乎被忽略

python - 将 Matlab 图叠加到 Python 图/图像上

python Pandas : Aggregate rows conditional value picking

Python 编程 - numpy polyfit 说 NAN

python - Pandas — 将数据集行从每个个体更改为每个操作的最简单方法

python - Flask:为什么我会收到 404 错误?

python - 如何使用 Python FileNotFoundError 打印丢失文件的名称?

python - 打印带有列表值的常规字典

python - 使用 Python 从 Blob URL 下载文件