Try numpy.clip :
>>> import numpy >>> a = numpy.arange(-10, 10) >>> a array([-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> a.clip(0, 10) array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
You can only click the bottom half with clip(0) .
>>> a = numpy.array([1, 2, 3, -4, 5]) >>> a.clip(0) array([1, 2, 3, 0, 5])
You can only pin the top half with clip(max=n) . (This is much better than my previous sentence, which included passing NaN into the first parameter and using out to force type input.):
>>> a.clip(max=2) array([ 1, 2, 2, -4, 2])
Another interesting approach is to use where :
>>> numpy.where(a <= 2, a, 2) array([ 1, 2, 2, -4, 2])
Finally, consider the aix answer. I prefer clip for simple operations because it is self-documenting, but its answer is preferable for more complex operations.