threshold in 2D numpy array

One solution:

result = (array < 25) * array

The first part array < 25 gives you an array of the same shape that is 1 (True) where values are less than 25 and 0 (False) otherwise. Element-wise multiplication with the original array retains the values that are smaller than 25 and sets the rest to 0. This does not change the original array

Another possibility is to set all values that are >= 25 to zero in the original array:

array[array >= 25] = 0

Leave a Comment