gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:35:54 27 4
gpt4 key购买 nike

给定一个 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 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]

sample 运行-

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 处腐 eclipse 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)

关于python - 如何找到 numpy 数组中零元素前面至少有 N-1 个连续零的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54241367/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com