| by Arround The Web | No comments

NumPy np.clip()

This article will explore the clip() function in NumPy. We will start with the function syntax, its parameters, and examples of using the function.

The clip() function in NumPy allows you to limit the values passed to it by specifying the min and max range values.

Function Syntax

The function syntax is as shown below:

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

Parameter Values

The function accepts the following parameters:

  1. a – refers to the input array.
  2. a_min – the minimum value that can be inserted in the array.
  3. a_max – the maximum value accepted by the array.
  4. out – specifies an output array to store the result.

Return Value

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.

Example #1

Consider the example shown below:

# import numpy
import numpy as np

arr = np.array([[1,2,3], [4,5,6]])
print(f"before:\n{arr}")
arr_clip = np.clip(arr, a_min=1, a_max=5)
print(f"after:\n{arr_clip}")

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:

Example #2

You can also pass an array to the a_min or a_max parameters. Consider the example below:

arr = np.array([[1,2,3], [4,5,6], [7,8,9], [10,11,12]])
print(f"before:\n{arr}")
arr_clip = np.clip(arr, a_min=[1,2,3], a_max=6)
print(f"after:\n{arr_clip}")

The code above should return:

Conclusion

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!!

Share Button

Source: linuxhint.com

Leave a Reply