clip() and round() (NumPy)

np.clip() limits array values to a range, replacing anything below the minimum or above the maximum with the boundary value. np.round() rounds elements to a given number of decimal places. Both are vectorized.

NumPy

clip(a, low, high) is the fast way to bound data: values under low become low and values over high become high, which is common for capping outliers or keeping pixel values in [0, 255]. Pass None for one bound to clip on only one side.

round(a, decimals) rounds every element, using banker's rounding (round-half-to-even) for ties, so 0.5 rounds to 0 and 1.5 rounds to 2 — worth knowing if you expect always-up rounding. Set decimals to a negative number to round to tens or hundreds.

Both operate element-wise across the whole array in compiled code, so they are far quicker than looping and applying Python's built-in round or min/max.

Syntax

np.clip(a, a_min, a_max)  |  np.round(a, decimals)

Examples

Python

import numpy as np
print(np.clip(np.array([-1, 5, 12]), 0, 10))

Output:

[ 0  5 10]

Learn it in a lesson

See also

Back to the Dictionary