Search code examples
pythonarraysnumpymask

masking a numpy array using an existing mask of the same shape


Say I have a numpy array mask called m1 = [[False, True, False], [True, False, True]] And I want to find a mask m2 such that its (i,j) entry is True iff j >= 0 and m1[i, j+1] == True. Any elegant and efficient ideas as to how to pull that off? Thanks


Solution

  • Here's a way slicing and using binary operators:

    m1 = np.array([[False, True, False], [True, False, True]])
    
    m2 = np.full(m1.shape, False)
    m2[:, :-1] = m1[:, 1:] | m2[:, :-1]
    

    print(m2)
    
    array([[ True, False, False],
           [False,  True, False]])