How to mask array in Numpy?

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

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.

See also  How to print full array in Numpy?

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

Now you can see which items in an array are greater than 0.1.

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

Use random_array[mask] to print only the items that match the mask.

See also  Handling FloatingPointError: Ensuring Numerical Stability in NumPy

'mask array numpy python

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