Masking numpy arrays#

Masking is the term used for selecting entries in arrays, e.g. depending on its content. In order to do this, we need to use numpy arrays.

First, we define a numpy array. Per definition it contains numbers:

import numpy
measurements = numpy.asarray([1, 17, 25, 3, 5, 26, 12])
array([ 1, 17, 25,  3,  5, 26, 12])

Next, we create a mask, e.g. a mask that defines all measurements which are above a given threshold:

mask = measurements > 10
array([False,  True,  True, False, False,  True,  True])

We can apply that mask to our data to retrieve a new array that only contains masked values.

array([17, 25, 26, 12])


Create a new mask for all measurements below 20.

Apply the mask to retrieve a new array with numbers below 20.

Compute the average of all numbers below 20.