4

I have a 2D array of masks that I want to collapse along axis 0 using logical OR operation for values that are True. I was wondering whether there was a numpy function to do this process. My code looks something like:

>>> all_masks
array([[False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False],
       [False,  True, False, ..., False,  True, False],
       [False, False, False, ..., False, False, False],
       [False,  True, False, ..., False,  True, False]])

>>> all_masks.shape
(6, 870)

>>> output_mask
array([False, True, False, ..., False, True, False])

>>> output_mask.shape
(870,)

I have achieved output_mask this process through using a for loop. However I know using a for loop makes my code slower (and kinda messy) so I was wondering whether this process could be completed through a function of numpy or likewise?

Code for collapsing masks using for loop:

mask_out = np.zeros(all_masks.shape[1], dtype=bool)
for mask in all_masks:
    mask_out = mask_out | mask

return mask_out
Max Collier
  • 573
  • 8
  • 24

2 Answers2

4

You can use ndarray.any:

all_masks = np.array([[False, False, False, False, False, False],
                      [False, False, False, False, False, False],
                      [False, False, False, False, False, False],
                      [False,  True, False, False,  True, False],
                      [False, False, False, False, False, False],
                      [False,  True, False, False,  True, False]])

all_masks.any(axis=0)

Output:

array([False,  True, False, False,  True, False])
iz_
  • 15,923
  • 3
  • 25
  • 40
  • 3
    @MaxCollier: Actually, I was wrong to claim that `np.any` short-circuits. It did at one point, but [currently, it does not](https://stackoverflow.com/a/45774536/190597). – unutbu Jan 14 '19 at 02:02
3

You could use np.logical_or.reduce:

In [200]: all_masks = np.array([[False, False, False, False, False, False],
       [False, False, False, False, False, False],
       [False, False, False, False, False, False],
       [False,  True, False, False,  True, False],
       [False, False, False, False, False, False],
       [False,  True, False, False,  True, False]])

In [201]: np.logical_or.reduce(all_masks, axis=0)
Out[207]: array([False,  True, False, False,  True, False])

np.logical_or is a ufunc, and every ufunc has a reduce method.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677