Numpy has many inbuilt functions that allow you to easily manipulate the array in an efficient way. Numpy clip is one of the functions that clip NumPy arrays in an Interval. In this entire tutorial, you will learn how to clip arrays in python using the Numpy clip method.
Before going to the coding part let’s learn the syntax for the clip method.
numpy.clip(a, a_min, a_max, out=None)
The explanation of the parameters is below.
a: It is the input array.
a_min: It is the minimum value you want to clip.
a_max: The maximum value you want to clip.
out: Use it if you want to output the results to another array.
Examples of How to use Numpy clip
Example 1: Simple use case of Numpy clip
Let’s create a NumPy array and apply np.clip() method to it. In my case, I am clipping the values between 3 and 9. Execute the below lines of code.
import numpy as np
array = np.arange(1,15)
clipped_array = np.clip(array, 3,9)
print(clipped_array)
Output

In the output you can see all the values less than 3 have clipped to 3 and all the values above 9, clipped to 9. In the same way, if you want to clip the values above 10 and below 5 then you will use the statement np. clip(array,5,10). Run the below code and see the output.
import numpy as np
array = np.arange(1,15)
clipped_array = np.clip(array, 5,10)
print(clipped_array)
Output

Example 2: Output The clipped array to another array
The above example was clipping the values of the array on the same created array. Suppose I want to output the results to another array. Then in this case you have to use the out parameters. The out parameter should be the same dimension as the input array. Execute the below lines of code.
import numpy as np
array = np.arange(1,15)
out = np.zeros_like(array)
clipped_array = np.clip(array, 2,6,out=out)
print(clipped_array)
Output

You can see the results have been assigned to another array.
These are examples of how to use np.clip() method in Python. I hope you have liked this tutorial. If you have any queries on it then you can contact us for more help.
Source:
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.