Applying multiple masks to arrays Applying multiple masks to arrays numpy numpy

Applying multiple masks to arrays


otherwise you can use boolean operators, let's define en example:

d=np.arange(10)masks = [d>5, d % 2 == 0, d<8]

you can use reduce to combine all of them:

from functools import reducetotal_mask = reduce(np.logical_and, masks)

you can also use boolean operators explicitely if you need to manually choose the masks:

total_mask = masks[0] & masks[1] & masks[2]


I think you're looking for the star operator:

fullmask = [all(mask) for mask in zip(*masks)]

...although I'm not sure I understand your data structure completely.


How about using numpy record arrays?

import numpy as np# create some datapixel = np.arange(4000)wave = pixel / 4000. + 5500flux = pixel / 4000. + 9.5 * 5500data = np.rec.fromarrays((pixel, wave, flux), names='pixel, wave, flux')mask = data.wave > 5500.25mask &= data.flux / data.wave > 8.5print data[mask].pixel.mean()