The clip() function in NumPy allows you to limit the values passed to it by specifying the min and max range values.
The function syntax is as shown below:
The function accepts the following parameters:
- a – refers to the input array.
- a_min – the minimum value that can be inserted in the array.
- a_max – the maximum value accepted by the array.
- out – specifies an output array to store the result.
The function will return an array with the specified elements of the input array. Any values less than a_min are replaced with a_min, while values greater than a_max are replaced with a max.
For example, if a_min = 1 and a_max = 1, values less than one are replaced with one and values greater than ten are replaced with 10.
Consider the example shown below:
In this example, we have an array with values ranging from 1 to 6. We then use the clip function and set the min value to 1 and the max value to 5.
Since six is greater than the max value, the function will replace it with five and return the array as shown:
You can also pass an array to the a_min or a_max parameters. Consider the example below:
The code above should return:
In this article, we discussed the clip function in NumPy and how to use it to limit the minimum and maximum values an array can accept.
Thanks for reading!!