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:

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

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:

snippet
import numpy as np
x= np.arange(12)
y=np.clip(x, 3, 10)
y

Output:

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:

snippet
import numpy as np
a = np.arange(12)
np.clip(a, 3, 9, out=a)
a

Output:

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:

snippet
import numpy as np
a = np.arange(12)
np.clip(a, [3, 4, 1, 1, 1, 4, 4, 4, 4, 4, 5, 6], 8)

Output:

Output
array([3, 4, 3, 3, 4, 5, 6, 7, 8, 8, 8, 8])
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +