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
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])