What is the numpy.clip() function in NumPy?

Overview

The clip() function in NumPy is used to place or clip a limit values in an input array that is passed to it.

Syntax

numpy.clip(a, a_min, a_max, out=None, **kwargs)
Syntax for the clip() function

Parameter values

The clip() function takes the following parameter values:

  • a: This represents the input array of values to clip. This is a required parameter value.
  • a_min and a_max: This represents the minimum and maximum values to clip the array. This is an optional parameter value.
  • out: This represents the location where the result is stored. This is an optional parameter value.
  • where: This is the condition over which the input is broadcast. At a given location where this condition is True, the resulting array is set to the ufunc result. Otherwise, the resulting array retains its original value. This is an optional parameter value.
  • kwargs: This represents the other keyword arguments. This is an optional parameter value.

Example

import numpy as np
# creating an input array of complex values
x = np.array([1, 3, 2, 2, 4, 5, 6, 7, 8, 9])
# implementing the clip() function
# let the minimum value of the array be 2 and the maximum 7
myarray = np.clip(x, 2, 7)
print(x)
print(myarray)

Explanation

  • Line 1: We import the numpy module.
  • Line 4: We create an array x that has complex values, using the array() function.
  • Line 8: We implement the clip() function on the input array by setting the minimum value of the array as 2 and the maximum value of the array as 7. We assign the result to a variable called myarray.
  • Line 10: We print the variable x.
  • Line 11: We print the variable myarray.

Free Resources