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

NumpyServer Side ProgrammingProgramming

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...\n", arr)

Get the type pf array −

print("\nArray type...\n", arr.dtype)

Get the dimensions of the Array −

print("\nArray Dimensions...\n",arr.ndim)

Get the shape of the Array −

print("\nOur Array Shape...\n",arr.shape)

Get the number of elements of the Array −

print("\nNumber of Elements in the Array...\n",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("\nDisplay the updated array...\n",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("\nResult...\n",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...\n", arr)

# Get the type pf array
print("\nArray type...\n", arr.dtype)

# Get the dimensions of the Array
print("\nArray Dimensions...\n",arr.ndim)

# Get the shape of the Array
print("\nOur Array Shape...\n",arr.shape)

# Get the number of elements of the Array
print("\nNumber of Elements in the Array...\n",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("\nDisplay the updated array...\n",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("\nResult...\n",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 -- --]
raja
Updated on 04-Feb-2022 11:08:23

Advertisements