NumPy - clip() function

The NumPy clip() function is used to clip (limit) the values in an array. 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.

Syntax

numpy.clip(a, a_min, a_max, out=None)

Parameters

 a Required. Specify the array containing elements to clip. array_like. a_min, a_max Optional. Specify minimum and maximum value. If None, clipping is not performed on the corresponding edge. Only one of a_min and a_max may be None. Both are broadcast against a. out Optional. Specify the destination to place the result. If provided, it must have a shape matching with the returned array.

Return Value

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.

Example:

In the example below, clip() function is used to clip the value of all elements of a given array.

import numpy as np

Arr = np.array([10, 20, 30, 40, 50, 60]).reshape(2,3)

#clipping elements of Arr
NewArr = np.clip(Arr, 25, 50)

#displaying the result
print("Original Array:")
print(Arr)
print("\nClipped Array:")
print(NewArr)

The output of the above code will be:

Original Array:
[[10 20 30]
[40 50 60]]

Clipped Array:
[[25 25 30]
[40 50 50]]

Example:

In the example below, clip() function is used to replace all negative values with 0.

import numpy as np

Arr = np.array([-10, -20, -30, 10, 20, 30]).reshape(2,3)

#clipping negative elements only
NewArr = np.clip(Arr, a_min=0, a_max=None)

#displaying the result
print("Original Array:")
print(Arr)
print("\nClipped Array:")
print(NewArr)

The output of the above code will be:

Original Array:
[[-10 -20 -30]
[ 10  20  30]]

Clipped Array:
[[ 0  0  0]
[10 20 30]]

❮ NumPy - Functions

5