Search code examples
pythonnumpymultidimensional-arrayvectorizationmasking

Python/Numpy: Combining boolean masks by row in 2D array


I have a 2D numpy array of boolean masks with n rows where each row is an array of m masks.

maskArr = [
            [[True, False, True, False], [True, True, False, True], [True, True, False, True]],
            [[False, True, False, True], [False, True, True, True], [True, True, False, True]],
            [[True, False, True, False], [True, True, False, True], [True, True, False, True]],
            [[False, True, False, True], [False, True, True, True], [True, True, False, True]],
            [[True, False, True, False], [True, True, False, True], [True, True, False, True]],
            [[False, True, False, True], [False, True, True, True], [True, True, False, True]]
          ]

Is there a way to vectorize the combining of mask arrays in each row to get the following result?

combinedMaskArr = [
                    [True, False, False, False],
                    [False, True, False, True],
                    [True, False, False, False],
                    [False, True, False, True],
                    [True, False, False, False],
                    [False, True, False, True]
                  ]

Thank you for any guidance or suggestions in advance.


Solution

  • You're trying to testing whether all elements are true along a specific axis. Use np.all

    np.all(maskArr, axis=1)
    

    Output

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