'Express 1d masked array as list of slices
I have a 1d numpy array with booleans values (mask) which I would like to convert into a list of slices where the mask is True, e.g.:
mask = [False, True, True, True, False, False, True, True]
and I would like to obtain
[slice(1, 4, None), slice(6, 8, None)]
The numpy masked array operations (in particular np.ma.clump_masked()) can do that, but the only way I found to use it would be to do the following:
np.ma.clump_masked(np.ma.masked_array(np.ones_like(mask), mask))
which yields exactly what I'm looking for:
[slice(1, 4, None), slice(6, 8, None)]
i.e., generating an array with the same shape as mask, applying the mask to it, and then computing mask_clumped() on that.
However, the np.ma.masked_array(np.ones_like(mask), mask)-step seems unnecessary to me. Is there any way to obtain the list of slices from a simplified operation which I would imagine to look like the following?
np.ma.clump_masked(mask)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
