Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy.where() detailed, step-by-step explanation / examples [closed]

I have trouble properly understanding numpy.where() despite reading the doc, this post and this other post.

Can someone provide step-by-step commented examples with 1D and 2D arrays?

like image 604
Alexandre Holden Daly Avatar asked Jan 07 '16 23:01

Alexandre Holden Daly


People also ask

What is NumPy explain in detail with example?

NumPy is a Python library used for working with arrays. It also has functions for working in domain of linear algebra, fourier transform, and matrices. NumPy was created in 2005 by Travis Oliphant. It is an open source project and you can use it freely. NumPy stands for Numerical Python.

What does NP where () return?

The numpy. where() function returns the indices of elements in an input array where the given condition is satisfied.

Why does NumPy where return a tuple?

numpy. where returns a tuple because each element of the tuple refers to a dimension. As you can see, the first element of the tuple refers to the first dimension of relevant elements; the second element refers to the second dimension.

How do you check if all values in a NumPy array are true?

If we have a Numpy array with boolean, True or False data, we can use np. all() to check if all of the elements are True .


1 Answers

After fiddling around for a while, I figured things out, and am posting them here hoping it will help others.

Intuitively, np.where is like asking "tell me where in this array, entries satisfy a given condition".

>>> a = np.arange(5,10) >>> np.where(a < 8)       # tell me where in a, entries are < 8 (array([0, 1, 2]),)       # answer: entries indexed by 0, 1, 2 

It can also be used to get entries in array that satisfy the condition:

>>> a[np.where(a < 8)]  array([5, 6, 7])          # selects from a entries 0, 1, 2 

When a is a 2d array, np.where() returns an array of row idx's, and an array of col idx's:

>>> a = np.arange(4,10).reshape(2,3) array([[4, 5, 6],        [7, 8, 9]]) >>> np.where(a > 8) (array(1), array(2)) 

As in the 1d case, we can use np.where() to get entries in the 2d array that satisfy the condition:

>>> a[np.where(a > 8)] # selects from a entries 0, 1, 2 

array([9])


Note, when a is 1d, np.where() still returns an array of row idx's and an array of col idx's, but columns are of length 1, so latter is empty array.

like image 129
Alexandre Holden Daly Avatar answered Sep 18 '22 09:09

Alexandre Holden Daly