Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collapse mask array along axis - Numpy in Python

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
like image 214
Max Collier Avatar asked Mar 05 '23 17:03

Max Collier


2 Answers

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])
like image 54
iz_ Avatar answered Mar 15 '23 20:03

iz_


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.

like image 44
unutbu Avatar answered Mar 15 '23 21:03

unutbu