Numpy clip() Function



The Numpy clip() function is used to limit the values in an array within a specified range. Any values smaller than the lower bound are replaced by the lower bound, and values larger than the upper bound are replaced by the upper bound. This function is particularly useful for normalizing data or constraining outputs.

We can also use the clip() function to apply constraints to arrays with different data types, ensuring that all values lie within the specified range. However, the function does not verify whether the lower bound is less than the upper bound. If the lower bound is accidentally set greater than the upper bound, the function will still execute but may produce unexpected or nonsensical results.

Syntax

Following is the syntax of the Numpy clip() function −

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

Parameters

Following are the parameters of the Numpy clip() function −

  • a: The input array.
  • a_min: The minimum value to clip the array values.
  • a_max: The maximum value to clip the array values.
  • out (optional): An alternative array to store the result. It must have the same shape as the input array.

Return Type

This function returns an array with the elements of a, but where values < a_min are replaced with a_min, and those values > a_max with a_max.

Example

Following is a basic example of using the Numpy clip() function to constrain values in an array −

import numpy as np  
my_Array = np.array([10, 20, 30, 40, 50])  
result = np.clip(my_Array, 15, 35)  
print("Clipped Array:", result)  

Output

Following is the output of the above code −

Clipped Array: [15 20 30 35 35]  

Example: Clipping Negative Values

The clip() function can also be used to replace all negative values in an array with zero, effectively normalizing the data to be non-negative −

import numpy as np  
array = np.array([-10, -5, 0, 5, 10])  
result = np.clip(array, 0, None)  
print("Clipped Array:", result)  

Output

Following is the output of the above code −

Clipped Array: [ 0  0  0  5 10]  

Example: Using clip() with Mixed Data Types

We can also use the clip() function to apply constraints to arrays with mixed data types. The input array is first cast to a compatible type, and then clipping is applied.

In the following example, we have clipped the elements of the mixed_Array that are less than 3 or greater than 6, ensuring all values lie within the specified range of 3 to 6 −

import numpy as np  
mixed_Array = np.array([1, 2.5, 4.5, 6, 8.9])  
result = np.clip(mixed_Array, 3, 6)  
print("Clipped Array:", result)  

Output

Following is the output of the above code −

Clipped Array: [3.  3.  4.5 6.  6. ]  
numpy_array_manipulation.htm
Advertisements