What is the clip() function for a 2-D array in Python?

The numpy.clip() method

The numpy.clip() function is used to clip a limit value in an input array. The input array can be 1-dimensional, 2-dimensional, etc.

In this article, we’ll focus on using the numpy.clip() method for a 2-dimensional array.

Note: A list of lists can be used to create a two-dimensional (2-D) array in Python.

Syntax

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

Parameters

  • a: This is the input (2-D) array of values.
  • a_min: (optional) Indicates the minimum values to clip the array.
  • a_max: (optional) Indicates the maximum values to clip the array.
  • out: (optional) Specify the location where the result is stored.

Return value

The numpy.clip() method returns an array containing elements of a. However, values less than the specified a_min are replaced with a_min, and values greater than the specified a_max are replaced with a_max.

Example

The following code shows how to use the numpy.clip() method for two-dimensional (2-D) arrays in Python.

# import numpy
import numpy as np
# create 2D array using np.array
a = np.array([[7,3,4,8], [2,6,9,5]])
# Create a min value
a_min = 3
# Create a max value
a_max = 8
# np.clip()
result = np.clip(a, a_min, a_max)
print(result)

Explanation

  • Line 2: We import the numpy library.
  • Lines 4: We create a 2D array called a.
  • Line 6: We create a min value and stored it in the variable a_min.
  • Line 8: We create a max value and stored it in the variable a_max.
  • Line 11: We use the np.clip() method to limit the input array a to a minimum of 3 and a maximum of 8.
  • Line 13: The result is displayed.

Note: Any value of array a smaller than the a_min is replaced by the a_min value and any value of array a greater than the a_max is replaced by the a_max value.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved