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])
                        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.        
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With