<p><strong>方法1</strong></p>
<p>我们可以使用<a href="https://www.numpy.org/devdocs/reference/generated/numpy.convolve.html" rel="noreferrer">^{<cd1>} convolution</a>-</p>
<pre><code>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]
</code></pre>
<p>样本运行-</p>
^{pr2}$
<p><strong>方法2</strong></p>
<p>另一种解决这个问题的方法可以看作是<code>1D</code>卷积方法的一种变体,它是使用<code>erosion</code>,因为如果你看一下输出,我们可以简单地从开始到<code>n-1</code>处侵蚀{<cd4>}的掩码。因此,我们可以使用<a href="https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.morphology.binary_erosion.html" rel="noreferrer">^{<cd6>} ^{<cd7>}</a>,它也允许我们用它的<code>origin</code>参数指定内核中心的部分,因此我们将避免任何切片。实现应该是这样的-</p>
<pre><code>from scipy.ndimage.morphology import binary_erosion
out = binary_erosion(a==0,np.ones(n),origin=(n-1)//2).astype(int)
</code></pre>