Understanding numpy.where

I am reading the documentation numpy.where(condition[, x, y]), but I cannot understand a small example:

>>> x = np.arange(9.).reshape(3, 3)
>>> np.where( x > 5 )
Out: (array([2, 2, 2]), array([0, 1, 2]))

Can someone explain how the result comes from?

+4
source share
2 answers

The first array ( array([2, 2, 2])) is the index of the rows, and the second ( array([0, 1, 2])) is the columns of those values ​​that are greater than 5.

You can use zipto get the exact index of values:

>>> zip(*np.where( x > 5 ))
[(2, 0), (2, 1), (2, 2)]

Or use np.dstack:

>>> np.dstack(np.where( x > 5 ))
array([[[2, 0],
        [2, 1],
        [2, 2]]])
+5
source

It prints the coordinates in your state

import numpy as np

x = np.arange(9.).reshape(3, 3)
print x
print np.where( x > 5 )

where print x prints:

[[ 0.  1.  2.]
 [ 3.  4.  5.]
 [ 6.  7.  8.]]

and np.where( x > 5 )prints the index location of all elements greater than 5

(array([2, 2, 2]), array([0, 1, 2]))

where 2.0 == 6 and 2.1 == 7 and 2.2 == 8

+2
source

All Articles