Enforce numeric limits
Preparing features or measurements for a bounded model input.
NumPy · Function
Clips array elements to an interval by replacing values below the lower bound or above the upper bound with the corresponding boundary. Bounds may be scalar or array-like and can be broadcast across the input.
np.clip applies lower and upper bounds element by element. Values below the lower bound become that bound, values above the upper bound become the upper bound, and values already inside remain unchanged; bounds and the input can be broadcast.
numpy.clip(a, a_min=<no value>, a_max=<no value>, out=None, *, min=<no value>, max=<no value>, **kwargs)| Name | Type | Description |
|---|---|---|
a | array_like | Input array containing the values to constrain. |
a_min | array_like, scalar, or None | Lower clipping limit; use None to leave the lower side unclipped. |
a_max | array_like, scalar, or None | Upper clipping limit; use None to leave the upper side unclipped. |
out | ndarray, optional | Optional destination array for the result; it may be a. |
min | array_like, scalar, or None | Alternative lower bound introduced alongside max; mutually exclusive with a_min. |
max | array_like, scalar, or None | Alternative upper bound introduced alongside min; mutually exclusive with a_max. |
kwargs | any | Additional keyword arguments passed to the underlying implementation. |
clipped_array — ndarray containing a with values below the lower limit replaced by that limit and values above the upper limit replaced by that limit.
import numpy as np
values = np.array([-2, 0.5, 3, 8])
clipped = np.clip(values, 0, 5)
print(clipped) # [0. 0.5 3. 5. ]Restricts every element to the inclusive interval from 0 through 5.
Preparing features or measurements for a bounded model input.
Keeping computed values within a valid display or protocol range.
Updating an existing ndarray without a separate destination.
np.clip(a, a_min, a_max) replaces values below a_min with a_min and values above a_max with a_max. It is equivalent to applying maximum with the lower bound and then minimum with the upper bound, but the documented function is faster.
Follow-up: What happens when the bounds are arrays? The bounds are broadcast against the input, allowing elementwise limits wherever their shapes are broadcast-compatible.
The input a is array-like, while a_min and a_max may be scalars, array-like values, or None. None disables clipping at that side, so at most one bound can be omitted this way.
Follow-up: Can both bounds be omitted? No: the function requires either the older positional bounds or the newer min/max keyword pair to define the operation.
out receives the result and must have a shape that can hold it. It may be the input array, enabling in-place clipping, and the output type is preserved.
Follow-up: Why use out? It can avoid allocating a separate result when an appropriately shaped writable array is available.
numpy.minimumnumpy.maximumnumpy.clip