NumPy clip()

The numpy.clip() function limits the values in an array to a specified range. Any values lower than the minimum threshold are set to the minimum, and any values higher than the maximum threshold are set to the maximum.

Syntax

</>
Copy
numpy.clip(a, a_min, a_max, out=None, *, min=None, max=None)

Parameters

ParameterTypeDescription
aarray_likeInput array containing elements to clip.
a_minarray_like or NoneMinimum value. Elements below this value are clipped to a_min. If None, no lower bound is applied.
a_maxarray_like or NoneMaximum value. Elements above this value are clipped to a_max. If None, no upper bound is applied.
outndarray, optionalOptional output array where the result is stored. It must have the same shape as the input array.
minarray_like or NoneAlternative for a_min, introduced in NumPy 2.1.0.
maxarray_like or NoneAlternative for a_max, introduced in NumPy 2.1.0.

Return Value

Returns an array where values lower than a_min are replaced with a_min, and values higher than a_max are replaced with a_max. The shape and type of the input array are preserved.


Examples

1. Clipping Values in a NumPy Array

In this example, we clip an array so that values are limited between 2 and 8.

</>
Copy
import numpy as np

# Define an array with values outside the clipping range
arr = np.array([1, 3, 5, 7, 9, 11])

# Clip values below 2 to 2, and above 8 to 8
clipped_arr = np.clip(arr, 2, 8)

# Print the result
print("Original array:", arr)
print("Clipped array:", clipped_arr)

Output:

Original array: [ 1  3  5  7  9 11]
Clipped array: [2 3 5 7 8 8]