繁体   English   中英

如何找到numpy数组中零元素前面至少有N-1个连续零的位置?

[英]How to find where in numpy array a zero element is preceded by at least N-1 consecutive zeros?

给定一个numpy数组(为了简单起见,让它成为一个数组),我怎样才能构造一个相同形状的新数组,其中1代表原始数组中的位置正好为零,前面至少为N-1连续零?

例如,实现具有两个参数的函数nzeros的最佳方法是什么,numpy数组和所需的最小连续零数:

import numpy as np
a = np.array([0, 0, 0, 0, 1, 0, 0, 0, 1, 1])
b = nzeros(a, 3)

函数nzeros(a, 3)应该返回

array([0, 0, 1, 1, 0, 0, 0, 1, 0, 0])

方法#1

我们可以使用1D卷积 -

def nzeros(a, n):
    # Define kernel for 1D convolution
    k = np.ones(n,dtype=int)

    # Get sliding summations for zero matches with that kernel
    s = np.convolve(a==0,k)

    # Look for summations that are equal to n value, which will occur for
    # n consecutive 0s. Remember that we are using a "full" version of
    # convolution, so there's one-off offsetting because of the way kernel
    # slides across input data. Also, we need to create 1s at places where
    # n consective 0s end, so we would need to slice out ending elements.
    # Thus, we would end up with the following after int dtype conversion
    return (s==n).astype(int)[:-n+1]

样品运行 -

In [46]: a
Out[46]: array([0, 0, 0, 0, 1, 0, 0, 0, 1, 1])

In [47]: nzeros(a,3)
Out[47]: array([0, 0, 1, 1, 0, 0, 0, 1, 0, 0])

In [48]: nzeros(a,2)
Out[48]: array([0, 1, 1, 1, 0, 0, 1, 1, 0, 0])

方法#2

另一种解决方法,这可以被认为是一1D卷积方法的一种变体,可能是使用erosion ,因为如果你看一下输出,我们可以简单地从开始直到n-1位置侵蚀0s的掩码。 因此,我们可以使用scipy.ndimage.morphology's binary_erosion ,它还允许我们用其origin arg指定内核中心的部分,因此我们将避免任何切片。 实现看起来像这样 -

from scipy.ndimage.morphology import binary_erosion

out = binary_erosion(a==0,np.ones(n),origin=(n-1)//2).astype(int)

使用for循环:

def nzeros(a, n):
  #Create a numpy array of zeros of length equal to n
  b = np.zeros(n)

  #Create a numpy array of zeros of same length as array a
  c = np.zeros(len(a), dtype=int)

  for i in range(0,len(a) - n):
    if (b == a[i : i+n]).all():  #Check if array b is equal to slice in a
      c[i+n-1] = 1

  return c

样本输出:

print(nzeros(a, 3))
[0 0 1 1 0 0 0 1 0 0]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM