NumPy clip()

The clip() function is used to limit the values in an array to a specified range.

import numpy as np

array1 = np.array([1, 2, 3, 4, 5])

# clip values in array1 between 2 and 4 using clip() clipped_array = np.clip(array1, 2, 4)
print(clipped_array) # Output : [2 2 3 4 4]

clip() Syntax

The syntax of clip() is:

numpy.clip(array, array_min, array_max, out=None)

clip() Arguments

The clip() function can take these arguments:

  • array - the input array
  • array_min - the minimum value
  • array_max - the maximum value
  • out (optional) - allows us to specify an array where the result will be stored

Note:

  • If any element in array is less than array_min, it will be set to array_min.
  • If any element in array is greater than array_max, it will be set to array_max.

clip() Return Value

The clip() method returns returns the clipped array, where the values are limited to the specified range.


Example 1: Clip an Array

import numpy as np

array1 = np.array([-2, 0, 3, 7, 10])

# clip values in array1 between 0 and 5 using clip() clipped_array = np.clip(array1, 0, 5)
print(clipped_array)

Output

[0 0 3 5 5]

In the above example, we have an array called array1 with values [-2, 0, 3, 7, 10].

We have used the np.clip() function to limit the values in array1 to the range from 0 to 5.

Any values less than 0 are clipped to 0, and any values greater than 5 are clipped to 5.


Example 2: Clip 2-D Array

import numpy as np

# create a 2-D array
array1 = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])

# use clip() to limit the values in the array to the range from 3 to 7
clipped_array = np.clip(array1, 3, 7)

print(clipped_array)

Output

[[3 3 3]
 [4 5 6]
 [7 7 7]]

Example 3: Use of out Argument in clip()

import numpy as np

array1 = np.array([1, 2, 3, 4, 5])

# create array of zeros with the same shape as array1
out_array = np.zeros_like(array1)  

# clip array1 and store the output in the out_array array np.clip(array1, 2, 4, out=out_array)
print(out_array)

Output

[2 2 3 4 4]