Home > Software engineering >  numpy bring values in a range
numpy bring values in a range

Time:01-24

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])

CodePudding user response:

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])

CodePudding user response:

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])
  •  Tags:  
  • Related