Mask array elements where invalid values NaNs or infs occur in Numpy


To mask an array where invalid values occur (NaNs or infs), use the numpy.ma.masked_invalid() method in Python Numpy. This function is a shortcut to masked_where, with condition = ~(np.isfinite(a)). Any pre-existing mask is conserved. Only applies to arrays with a dtype where NaNs or infs make sense (i.e. floating point types), but accepts any array_like object.

A masked array is the combination of a standard numpy.ndarray and a mask. A mask is either nomask, indicating that no value of the associated array is invalid, or an array of booleans that determines for each element of the associated array whether the value is valid or not.

Steps

At first, import the required library −

import numpy as np
import numpy.ma as ma

Create an array with float elements using the numpy.array() method −

arr = np.array([91.6, 73.8, 29.2, 49.9, 39.7, 73.5, 87.6, 51.1])
print("Array...
", arr)

Get the type pf array −

print("
Array type...
", arr.dtype)

Get the dimensions of the Array −

print("
Array Dimensions...
",arr.ndim)

Get the shape of the Array −

print("
Our Array Shape...
",arr.shape)

Get the number of elements of the Array −

print("
Number of Elements in the Array...
",arr.size)

Set NaNs or infs for array values −

arr[1] = np.NaN
arr[3] = np.PINF
arr[6] = np.NaN
arr[7] = np.PINF
print("
Display the updated array...
",arr)

To mask an array where invalid values occur (NaNs or infs), use the numpy.ma.masked_invalid() method. Here, we will set the interval i.e. to mask between 55 and 90 −

print("
Result...
",ma.masked_invalid(arr))

Example

import numpy as np
import numpy.ma as ma

# Create an array with float elements using the numpy.array() method
arr = np.array([91.6, 73.8, 29.2, 49.9, 39.7, 73.5, 87.6, 51.1])
print("Array...
", arr) # Get the type pf array print("
Array type...
", arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Get the number of elements of the Array print("
Number of Elements in the Array...
",arr.size) # Set NaNs or infs for array values arr[1] = np.NaN arr[3] = np.PINF arr[6] = np.NaN arr[7] = np.PINF print("
Display the updated array...
",arr) # To mask an array where invalid values occur (NaNs or infs), use the numpy.ma.masked_invalid() method in Python Numpy # Here, we will set the interval i.e. to mask between 55 and 90 print("
Result...
",ma.masked_invalid(arr))

Output

Array...
[91.6 73.8 29.2 49.9 39.7 73.5 87.6 51.1]

Array type...
float64

Array Dimensions...
1

Our Array Shape...
(8,)

Number of Elements in the Array...
8

Display the updated array...
[91.6 nan 29.2 inf 39.7 73.5 nan inf]

Result...
[91.6 -- 29.2 -- 39.7 73.5 -- --]

Updated on: 04-Feb-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements