NumPy | clip method
Start your free 7-days trial now!
Numpy's clip(~)
method is used to ensure that the values of the input array are between a particular range.
Parameters
1. a
| array_like
The input array.
2. a_min
| scalar
or array_like
or None
The lower bound to clip. Values that are smaller than a_min
will be replaced by a_min
. You can ignore the lower bound by setting None
.
3. a_max
| scalar
or array_like
or None
The upper bound to clip. Values that are larger than a_max
will be replaced by a_max
. You can ignore the upper bound by setting None
.
Return value
A Numpy array with the values of the input array clipped as per your parameters.
Examples
Specifying both lower and upper bound
np.clip(x, 2, 4)
array([2, 2, 3, 4, 4])
Notice how the value 1
was clipped up to 2
, while the value 5
is clipped down to 4
.
Not specifying a lower bound
Set None
for the second parameter:
np.clip(x, None, 4)
array([1, 2, 3, 4, 4])
Not specifying an upper bound
Set None
for the third parameter:
np.clip(x, 2, None)
array([2, 2, 3, 4, 5])
Clipping a 2D array
Clipping a multi-dimensional array is slightly tricky. Consider the following example:
np.clip(x, [2,3], [4,5])
array([[2, 3], [3, 4], [4, 5]])
Here, the first row [1,2]
is clipped by the lower bound [2,3]
- the clipping is done element-wise and so since 1<2
and 2<3
, both values are clipped up to [2,3]
.