Reputation: 1
Is there a more elegant way of bringing values in a numpy array in the range 0-50?
x = np.array([-5, 6, 24, 51, 50, 40])
array([-5, 6, 24, 51, 50, 40])
x = np.where(x < 0, 0, x)
x = np.where(x > 50, 50, x)
array([ 0, 6, 24, 50, 50, 40])
Upvotes: 0
Views: 90
Reputation: 1
Just found out there is https://numpy.org/doc/stable/reference/generated/numpy.clip.html#numpy.clip
np.clip(x, 0, 50)
array([ 0, 6, 24, 50, 50, 40])
Upvotes: 0
Reputation: 231540
In [49]: x = np.array([-5, 6, 24, 51, 50, 40])
A couple of alternatives:
In [50]: np.clip(x,0,50)
Out[50]: array([ 0, 6, 24, 50, 50, 40])
In [52]: np.minimum(np.maximum(x,0),50)
Out[52]: array([ 0, 6, 24, 50, 50, 40])
Upvotes: 3