Mask an array where the data is exactly equal to value in Numpy

NumpyServer Side ProgrammingProgramming

To mask an array where the data is exactly equal to value, use the numpy.ma.masked_object() method in Python Numpy. This function is similar to masked_values, but only suitable for object arrays: for floating point, use masked_values instead.

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 int elements using the numpy.array() method −

arr = np.array([[71, 55, 91], [82, 33, 39], [73, 82, 51], [90, 45, 82]])
print("Array...\n", arr)

Get the type of 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)

To mask an array where the data is exactly equal to value, use the numpy.ma.masked_object() method in Python Numpy −

print("\nResult...\n",np.ma.masked_object(arr, 82))

Example

import numpy as np
import numpy.ma as ma

# Create an array with int elements using the numpy.array() method
arr = np.array([[71, 55, 91], [82, 33, 39], [73, 82, 51], [90, 45, 82]])
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)

# To mask an array where the data is exactly equal to value, use the numpy.ma.masked_object() method in Python Numpy
print("\nResult...\n",np.ma.masked_object(arr, 82))

Output

Array...
[[71 55 91]
[82 33 39]
[73 82 51]
[90 45 82]]

Array type...
int64

Array Dimensions...
2

Our Array Shape...
(4, 3)

Number of Elements in the Array...
12

Result...
[[71 55 91]
[-- 33 39]
[73 -- 51]
[90 45 --]]
raja
Updated on 04-Feb-2022 11:14:12

Advertisements