Numpy array manipulation within range of columns and rows
<p>I have a numpy boolean 2D array that represents a grayscale image which is essentially an unfilled shape (triangle, square, circle) consisting of <code>True</code> for white pixels, and <code>False</code> for black pixels. I would like to add a black fill by modifying the white pixels to black pixels.</p>

<pre><code>array([[True, True, True, False, False, False, False, False, True, True, True],
       [True, True, True, False,  True,  True,  True, False, True, True, True],
       [True, True, True, False,  True,  True,  True, False, True, True, True],
       [True, True, True, False,  True,  True,  True, False, True, True, True],
       [True, True, True, False, False, False, False, False, True, True, True]])
</code></pre>

<p>(The 9 <code>True</code> values in a square in the middle of this array should become <code>False</code>.)</p>

<p>Is there a numpy slice method that will make this easy/fast? Something that I can modify all <code>True</code>s anytime there's a <code>False</code> followed by a <code>True</code> until the next instance of a <code>False</code>?</p>

<p>Based on your logic, you can replace all values between the first False and the last False with False:</p>

<pre><code>def mutate(A):
    ind = np.where(~A)[0]
    if len(ind) != 0:
        A[ind.min():ind.max()] = False
    return A


np.apply_along_axis(mutate, 1, arr)

# array([[ True,  True,  True, False, False, False, False, False,  True,
#          True,  True],
#        [ True,  True,  True, False, False, False, False, False,  True,
#          True,  True],
#        [ True,  True,  True, False, False, False, False, False,  True,
#          True,  True],
#        [ True,  True,  True, False, False, False, False, False,  True,
#          True,  True],
#        [ True,  True,  True, False, False, False, False, False,  True,
#          True,  True]], dtype=bool)
</code></pre>

python arrays performance numpy