Search code examples
pythonarraysnumpymasking

Slice a broadcast object?


I have a 2-dimensional array that represents a mask of a 3-dimensional array, and can be broadcast as such. e.g.:

>>> mask.shape
(101, 100)
>>> cube.shape
(500, 101, 100)

What is the best way to create a broadcastable object like mask (which is an array) that can be indexed with the same views as cube, returning the same mask? i.e.:

>>> cube[100,:,:]
<some image>
>>> mask[100,:,:]
<mask>

so mask[n,:,:] would return mask for any n, or better yet any n that could be used to index cube.

Importantly, I want to do this without making mask larger in memory (e.g., by doing bigger_mask = np.ones([500,1,1])*self._mask[None,:,:])


Solution

  • Something like this?

    >>> from numpy.lib.stride_tricks import as_strided
    >>> mask = np.random.randint(2, size=(101, 100)).astype(bool)
    >>> mask_view  = as_strided(mask, shape=(500,)+mask.shape,
    ...                         strides=(0,)+mask.strides)
    >>> mask_view.shape
    (500, 101, 100)
    >>> np.array_equal(mask_view[0], mask_view[499])
    True
    >>> np.all(mask_view == 0)
    False
    >>> mask[:] = 0
    >>> np.all(mask_view == 0)
    True