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 numpyimport numpy as np# create 2D array using np.arraya = np.array([[7,3,4,8], [2,6,9,5]])# Create a min valuea_min = 3# Create a max valuea_max = 8# np.clip()result = np.clip(a, a_min, a_max)print(result)
Explanation
- Line 2: We import the
numpylibrary. - 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 arrayato a minimum of3and a maximum of8. - Line 13: The result is displayed.
Note: Any value of array
asmaller than thea_minis replaced by thea_minvalue and any value of arrayagreater than thea_maxis replaced by thea_maxvalue.
Free Resources