如何在numpy数组中找到一个零元素前面至少有N1个连续的零?

2024-03-29 14:59:24 发布

您现在位置:Python中文网/ 问答频道 /正文

给定一个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)应返回

^{pr2}$

Tags: 方法函数importnumpy参数asnp数组
2条回答

方法1

我们可以使用^{} convolution-

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]

样本运行-

^{pr2}$

方法2

另一种解决这个问题的方法可以看作是1D卷积方法的一种变体,它是使用erosion,因为如果你看一下输出,我们可以简单地从开始到n-1处侵蚀{}的掩码。因此,我们可以使用^{} ^{},它也允许我们用它的origin参数指定内核中心的部分,因此我们将避免任何切片。实现应该是这样的-

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

样本输出:

^{pr2}$

相关问题 更多 >