I think both the fastest and most concise way to do this is to use NumPy’s built-in Fancy indexing. If you have an
arr, you can replace all elements
>255 with a value
x as follows:
arr[arr > 255] = x
I ran this on my machine with a 500 x 500 random matrix, replacing all values >0.5 with 5, and it took an average of 7.59ms.
In : import numpy as np In : A = np.random.rand(500, 500) In : timeit A[A > 0.5] = 5 100 loops, best of 3: 7.59 ms per loop