How to set the minimum and maximum value for each item in a Numpy array?

There are several ways of doing so. First, using a numpy function as proposed by Sridhar Murali :

a = np.array([1, 100, 123, -400, 85, -98]) 
np.clip(a,-100,90)

Second, using numpy array comparison :

a = np.array([1, 100, 123, -400, 85, -98])
a[a>90] = 90
a[a<-100] = -100

Third, if a numpy is not required for the rest of your code, using list comprehension :

a = [1, 100, 123, -400, 85, -98]
a = [-100 if x<-100 else 90 if x>90 else x for x in a]

They all give the same result :

a = [1, 90, 90, -100, 85, -98]

As for coding style, I would prefer numpy comparison or list comprehension as they state clearly what is done, but it is up to you really. As for speed, with timeit.repeat on 100000 repetitions, I get on average, from the best to the worst :

  1. 4.8e-3 sec for list comprehension
  2. 1.8e-1 sec for numpy array comparison
  3. 2.7e-1 sec for np.clip function

Clearly, if an array is not necessary afterwards, list comprehension is the way to go. And if you need an array, direct comparison is almost twice more efficient that the clip function, while more readable.


I think the easiest way for you to get the result is using the clip function from numpy.

import numpy as np
a = np.array([1, 100, 123, -400, 85, -98])
np.clip(a,-100,90)