numpy
  1. numpy-numpyclip

numpy.clip()

The numpy.clip() function belongs to the NumPy library of Python. It is used to limit the values in a given NumPy array to a specified range using the minimum and maximum values. It returns an array where the values outside the specified range are clipped to the range's corners.

Syntax

Following is the syntax for using the numpy.clip() function:

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

Here, a is the input array, a_min and a_max represent the minimum and maximum values that the values in the input array need to be clipped to, and out is the optional output array.

Example

The following example demonstrates the use of the numpy.clip() function:

import numpy as np

# creating an input array
input_array = np.array([1, 6, 3, 8, 5, -2, -6, 9])

# applying clip() function to limit the values within 2 and 8
output_array = np.clip(input_array, 2, 8)

print("Input Array:", input_array)
print("Output Array:", output_array)

The output of this program will be:

Input Array: [ 1  6  3  8  5 -2 -6  9]
Output Array: [2 6 3 8 5 2 2 8]

Explanation

In the example above, first, we create an input array input_array using the numpy.array() function. Then, we apply the numpy.clip() function on the input array to limit the values within 2 and 8 using the minimum and maximum values for clipping.

The resulting output array is output_array, which is stored in the variable of the same name. Finally, we print both the input and output arrays to the console.

Use

The numpy.clip() function is used to limit the values in a NumPy array to a specified range using the minimum and maximum values. It can be used in various applications involving data processing and analysis.

Important Points

  • The numpy.clip() function returns an array where the values outside the range specified by a_min and a_max are clipped to these values.
  • If a_min is None, then the minimum value of the input array is used as a_min.
  • If a_max is None, then the maximum value of the input array is used as a_max.
  • The optional out parameter can be used to specify the output array where the result will be stored.

Summary

The numpy.clip() function is used to limit the values in a NumPy array to a specified range using minimum and maximum values. It returns an array where the values outside of the range are clipped to the minimum or maximum. This function is useful for data processing and analysis, where the values need to be within a certain range.

Published on: