Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

threshold in 2D numpy array

Tags:

python

numpy

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.

like image 235
physics_for_all Avatar asked Apr 19 '16 13:04

physics_for_all


People also ask

How do you find the minimum value of a 2d array Numpy?

min to return the minimum value, or equivalently for an array arrname use arrname. min() . As you mentioned, numpy. argmin returns the index of the minimum value (of course, you can then use this index to return the minimum value by indexing your array with it).

What is datetime64 in Numpy?

datetime64() method, we can get the date in a numpy array in a particular format i.e year-month-day by using numpy. datetime64() method. Syntax : numpy.datetime64(date) Return : Return the date in a format 'yyyy-mm-dd'.

What is Numpy Timedelta?

NumPy allows the subtraction of two datetime values, an operation which produces a number with a time unit. Because NumPy doesn't have a physical quantities system in its core, the timedelta64 data type was created to complement datetime64 .


2 Answers

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
like image 200
MB-F Avatar answered Oct 20 '22 12:10

MB-F


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.

like image 43
Asad-ullah Khan Avatar answered Oct 20 '22 10:10

Asad-ullah Khan