Javatpoint Logo
Javatpoint Logo

numpy.clip() in Python

For clipping the values in an array, the numpy module of Python provides a function called numpy.clip(). In the clip() function, we will pass the interval, and the values which are outside the interval will be clipped for the interval edges.

If we specify an interval of [1, 2] then the values smaller than 1 become 1 and larger than 2 is 2. This function is similar to numpy.maximum(x_min, numpy.maximum(x, x_max)). But it is faster than np.maximum(). In numpy.clip(), there is no need to perform check for ensuring x_min < x_max.

Syntax:

Parameters:

x: array_like

This parameter defines the source array whose elements we want to clip.

x_min: None, scalar, or array_like

This parameter defines the minimum value for clipping values. On the lower interval edge, clipping is not required.

x_max: None, scalar, or array_like

This parameter defines the maximum value for clipping values. On the upper interval edge, clipping is not required. The three arrays are broadcasted for matching their shapes with x_min and x_max arrays. This will be done only when x_min and x_max are array_like.

out: ndaaray(optional)

This parameter defines the ndarray in which the result will be stored. For in-place clipping, this can be an input array. The data type of this 'out' arrays have the right shape for holding the output.

Returns

clip_arr: ndarray

This function returns an array that contains the elements of 'x' but the values which are less than the x_min, they get replaced with x_min, and those which are greater than x_max, they get replaced with x_max.

Example 1:

Output:

array([ 3,  3,  3,  3,  4,  5,  6,  7,  8,  9, 10, 10])

In the above code

  • We have imported numpy with alias name np.
  • We have created an array 'x' using arange() function.
  • We have declared the variable 'y' and assigned the returned value of clip() function.
  • We have passed the array 'x', x_min, and x_max value in the function
  • Lastly, we tried to print the value of 'y'.

In the output, a ndarray is shown, which contains elements ranging from 3 to 10.

Example 2:

Output:

array([3, 3, 3, 3, 4, 5, 6, 7, 8, 9, 9, 9])
 array([3, 3, 3, 3, 4, 5, 6, 7, 8, 9, 9, 9])

Example 3:

Output:

array([3, 4, 3, 3, 4, 5, 6, 7, 8, 8, 8, 8])






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA