Let’s see how to mask an array in the Numpy Python library.
Array masking, also known as boolean indexing, is a fundamental technique in NumPy for selectively accessing and manipulating elements in an array based on a condition. It allows you to create a mask – a boolean array – that corresponds to your original array, where True values indicate elements that meet a specific criterion.
Let’s say we have an array in Numpy.
How to use numpy mask?
Everything is OK except we need an additional mask for the given array. Let’s say I’d like to add a mask to see only elements of an array greater than 0.1.
First, let’s define the mask and see which elements are greater than 0.1.
import numpy as np random_array = np.random.random((1, 4)) print(random_array) mask = random_array > 0.1 print(mask)
The mask variable is now a boolean array of the same shape as random_array. Each element in mask is True where the corresponding element in random_array is greater than 0.1, and False otherwise.
How to return elements matching the mask?
There is also the possibility to display only items that match the mask.
import numpy as np random_array = np.random.random((1, 4)) print(random_array) mask = random_array > 0.1 print(mask) print(random_array[mask])
To display only the elements that correspond to True values in the mask, utilize the syntax random_array[mask].
The mask works and only values greater than 0.1 are displayed.