physics_for_all
physics_for_all

Reputation: 2263

threshold in 2D numpy array

I have an array of shape 512x512 which contains numbers between 0 and 100 at ith and jth position. Now I want to select array[i,j] < 25 and zero at other places. I have tried with array = array[where(array<25)], which gives me a 1D array, but I want 2D. Please help me to solve this.

Upvotes: 26

Views: 81786

Answers (2)

Asad-ullah Khan
Asad-ullah Khan

Reputation: 1863

I also wanted to add that you can take advantage of numpy views to achieve this:

>>> a = np.asarray([ [1,2], [3,4], [4,1], [6,2], [5,3], [0,4] ])
>>> b = a[:, 1] # lets say you only care about the second column
>>> b[b > 3] = 0
>>> print(a)
[[1 2]
 [3 0]
 [4 1]
 [6 2]
 [5 3]
 [0 0]]

This is nice when you want the values to be something other than 0.

Upvotes: 1

MB-F
MB-F

Reputation: 23647

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

Upvotes: 58

Related Questions