numpy.clip() in Python


The Python numpy.clip() function used to clip (limit) the values in an given array. With given interval values outside the interval edges will be clipped to the interval edges.

Basic Syntax

Following is the basic syntax for numpy.clip() function in Python:

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

And the parameters are:

Parameter Description
arr This is input array.
a_min The minimum value. If None provided the cliping is not performed on lower edges. Not more than one of a_min and a_max should be None. If one of a_min and a_max is array-like then three arrays will be broadcasted.
a_max The maximum value. If None provided the cliping is not performed on upper edges. Not more than one of a_min and a_max should be None. If one of a_min and a_max is array-like then three arrays will be broadcasted.

Return Value

This function returns 2D specialized array from a string of data or array-like object.

Example

Following are the examples:

Example 1

# Python3 program for demonstration of clip() function 

# importing the numpy 
import numpy as np 


input_array = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] 
print ("The input array : ", input_array) 

output_array = np.clip(input_array, a_min =[50, 30, 20, 50, 20, 20, 80, 80, 100, 90], a_max = 70) 
print ("The output array : ", output_array) 

The output for the above program is as given below:

The input array : [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
The output array : [ 50, 30, 30, 50, 50, 60, 80, 80, 100, 90]

Example 2

# Python program for illustration of numpy.clip() function 

# importing the numpy module
import numpy as np 

input_array = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] 
print ("The input array : ", input_array) 

output_array = np.clip(input_array, a_min = 30, a_max = 80) 
print ("The output array : ", output_array)   

The output for the above program is as given below:

The input array : [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
The output array : [30, 30, 30, 40, 50, 60, 70, 80, 80, 80]