Mask an array inside a given interval in Numpy


To mask an array inside a given interval, use the numpy.ma.masked_inside() method in Python Numpy. Shortcut to masked_where, where condition is True for x inside the interval [v1,v2] (v1 <= x <= v2). The boundaries v1 and v2 can be given in either order.

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([[83, 55, 73], [90, 49, 39], [73, 87, 51], [82, 45, 67]])
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 inside a given interval, use the numpy.ma.masked_inside() method in Python Numpy. Here, we will set the interval i.e. to mask between 55 and 90 −

print("
Result...
",np.ma.masked_inside(arr, 55, 90))

Example

import numpy as np
import numpy.ma as ma

# Create an array with int elements using the numpy.array() method
arr = np.array([[83, 55, 73], [90, 49, 39], [73, 87, 51], [82, 45, 67]])
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 inside a given interval, use the numpy.ma.masked_inside() method in Python Numpy # Here, we will set the interval i.e. to mask between 55 and 90 print("
Result...
",np.ma.masked_inside(arr, 55, 90))

Output

Array...
[[83 55 73]
[90 49 39]
[73 87 51]
[82 45 67]]

Array type...
int64

Array Dimensions...
2

Our Array Shape...
(4, 3)

Number of Elements in the Array...
12

Result...
[[-- -- --]
[-- 49 39]
[-- -- 51]
[-- 45 --]]

Updated on: 04-Feb-2022

354 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements