Clip (limit) the values in a Numpy array


To clip (limit) the values in an array, use the np.ma.clip() method in Python Numpy. Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of [0, 1] is specified, values smaller than 0 become 0, and values larger than 1 become 1. Equivalent to but faster than np.minimum(a_max, np.maximum(a, a_min)).

The out is where the results will be placed in this array. It may be the input array for in-place clipping. out must be of the right shape to hold the output. Its type is preserved.

The function returns an array with the elements of a, but where values < a_min are replaced with a_min, and those > a_max with a_max.

Steps

At first, import the required library −

import numpy as np

Create an array with int elements using the numpy.array() method −

arr = np.array([25, 32, 38, 47, 53, 66, 73, 79, 88, 95, 108])
print("Array...
", arr)

Create a masked array and mask some of them as invalid −

maskArr = ma.masked_array(arr, mask =[0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0])
print("
Our Masked Array...
", maskArr)

Get the type of the masked array −

print("
Our Masked Array type...
", maskArr.dtype)

Get the dimensions of the Masked Array −

print("
Our Masked Array Dimensions...
",maskArr.ndim)

Get the shape of the Masked Array −

print("
Our Masked Array Shape...
",maskArr.shape)

Get the number of elements of the Masked Array −

print("
Number of elements in the Masked Array...
",maskArr.size)

To clip (limit) the values in an array, use the np.ma.clip() method in Python Numpy −

print("
Result..
.", np.ma.clip(maskArr, 50, 80 ))

Example

import numpy as np
import numpy.ma as ma

# Create an array with int elements using the numpy.array() method
arr = np.array([25, 32, 38, 47, 53, 66, 73, 79, 88, 95, 108])
print("Array...
", arr) # Create a masked array and mask some of them as invalid maskArr = ma.masked_array(arr, mask =[0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0]) print("
Our Masked Array...
", maskArr) # Get the type of the masked array print("
Our Masked Array type...
", maskArr.dtype) # Get the dimensions of the Masked Array print("
Our Masked Array Dimensions...
",maskArr.ndim) # Get the shape of the Masked Array print("
Our Masked Array Shape...
",maskArr.shape) # Get the number of elements of the Masked Array print("
Number of elements in the Masked Array...
",maskArr.size) # To clip (limit) the values in an array, use the np.ma.clip() method in Python Numpy print("
Result..
.", np.ma.clip(maskArr, 50, 80 ))

Output

Array...
[ 25 32 38 47 53 66 73 79 88 95 108]

Our Masked Array...
[25 -- 38 47 -- 66 73 79 88 -- 108]

Our Masked Array type...
int64

Our Masked Array Dimensions...
1

Our Masked Array Shape...
(11,)

Number of elements in the Masked Array...
11

Result..
. [50 -- 50 50 -- 66 73 79 80 -- 80]

Updated on: 22-Feb-2022

679 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements