Mask an array where a condition is met in Numpy


To mask an array where a condition is met, use the numpy.ma.masked_where() method in Python Numpy. Return the array to mask as an array masked where condition is True. Any masked values of a or condition are also masked in the output.

The condition parameter sets the masking condition. When condition tests floating point values for equality, consider using masked_values instead. The copy parameter, If True (default) make a copy of a in the result. If False modify a in place and return a view.

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

To mask an array where a condition is met, use the numpy.ma.masked_where() method in Python Numpy. Here, all the elements above 60 will get masked −

print("
Result...
",np.ma.masked_where(arr > 60, arr))

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...
", 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) # To mask an array where a condition is met, use the numpy.ma.masked_where() method in Python Numpy # Here, all the elements above 60 will get masked print("
Result...
",np.ma.masked_where(arr > 60, arr))

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...
[[-- 55 --]
[-- 33 39]
[-- -- 51]
[-- 45 --]]

Updated on: 04-Feb-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements