# Mask an array outside a given interval in Numpy

NumpyServer Side ProgrammingProgramming

#### Python Data Science basics with Numpy, Pandas and Matplotlib

Most Popular

63 Lectures 6 hours

#### Data Analysis using NumPy and Pandas

19 Lectures 8 hours

#### Numpy with Python

Most Popular

12 Lectures 3 hours

To mask an array outside a given interval, use the numpy.ma.masked_outside() method in Python Numpy. Shortcut to masked_where, where condition is True for x outside the interval [v1,v2] (x < 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...\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 7minus;

print("\nNumber of Elements in the Array...\n",arr.size)

To mask an array outside a given interval, use the numpy.ma.masked_outside() method in Python Numpy. Here, we will set the interval i.e. to mask outside 65 and 85 −

print("\nResult...\n",np.ma.masked_inside(arr, 65, 85))


## 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...\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 outside a given interval, use the numpy.ma.masked_outside() method in Python Numpy
# Here, we will set the interval i.e. to mask outside 65 and 85
print("\nResult...\n",np.ma.masked_inside(arr, 65, 85))

## 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...
[[-- 55 --]
[90 49 39]
[-- 87 51]
[-- 45 --]]