How to mask array in Numpy?

Let’s see how to mask an array in the Numpy Python library.

'mask array numpy python

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.

See also  Ways how to convert numpy array to string

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)

mask numpy true false

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.

See also  How to resolve TypeError: Cannot cast scalar from dtype('float64') to dtype('int64') according to the rule 'safe'

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].

'mask array numpy python

The mask works and only values greater than 0.1 are displayed.

See also  How to count number of zeros in Numpy array?