Masking numpy arrays
Contents
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])
measurements
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
mask
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.
measurements[mask]
array([17, 25, 26, 12])
Exercises#
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.