np.clip(arr, lo, hi) leaves elements already between lo and hi untouched, replaces any element below lo with lo, and replaces any element above hi with hi — a fast, vectorized way to enforce a valid range on an array's values without writing an explicit loop or boolean-indexing assignment. Passing None for either bound leaves that side unconstrained, letting you clip only a lower bound, only an upper bound, or both.
1Understanding np.clip()
np.clip(arr, lo, hi) leaves elements already between lo and hi untouched, replaces any element below lo with lo, and replaces any element above hi with hi — a fast, vectorized way to enforce a valid range on an array's values without writing an explicit loop or boolean-indexing assignment. Passing None for either bound leaves that side unconstrained, letting you clip only a lower bound, only an upper bound, or both.
Use np.clip() to enforce a valid value range in one call, such as keeping pixel values within 0-255 or probabilities within 0-1, instead of writing two separate boolean-indexing assignments for the lower and upper bound.
import numpy as np
arr = np.array([-5, 0, 5, 10, 15])
print(np.clip(arr, 0, 10))2Practical Example
Here is a real-world application of np.clip() showing how it is used in production NumPy code.
import numpy as np
pixels = np.array([-20, 100, 260, 128])
print(np.clip(pixels, 0, 255))3Best Practices
Follow these guidelines when working with np.clip():
1. Use np.clip() instead of two separate boolean-indexing assignments when constraining values to a range
2. Pass None for one bound when you only need to enforce a floor or a ceiling, not both
3. Clip intermediate results in numerically unstable calculations, like probabilities that should stay strictly between 0 and 1, to avoid downstream errors from values that drift slightly out of a valid range
Tip: Use np.clip() to enforce a valid value range in one call, such as keeping pixel values within 0-255 or probabilities within 0-1, instead of writing two separate boolean-indexing assignments for the lower and upper bound.
import numpy as np
arr = np.array([-5, 0, 5, 10, 15])
print(np.clip(arr, 0, 10))