Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over the output of `np.where`

I have a 3D array and use np.where to find elements that meet a certain condition. The output of np.where is a tuple of three 1D arrays, each giving the indices along a single axis. I'd like to iterate over this output and print out the index of each point in the matrix that met the condition.

One way to do it is:

indices = np.where(myarray == 0)
for i in range(0, len(indices[0])):
    print indices[0][i], indices[1][i], indices[2][i]

However, it looks a bit cumbersome and I was wondering if there's a better way?

like image 740
John Manak Avatar asked Feb 19 '14 16:02

John Manak


People also ask

What does NP where output?

If you do this, Numpy where will simply output the index positions of the elements for which condition is True .

Can you iterate over an NP array?

NumPy package contains an iterator object numpy. It is an efficient multidimensional iterator object using which it is possible to iterate over an array. Each element of an array is visited using Python's standard Iterator interface.

How do you iterate through values?

Iterating over values In order to iterate over the values of the dictionary, you simply need to call values() method that returns a new view containing dictionary's values.


1 Answers

Use zip

indices = zip(*np.where(myarray == 0))

Then you can do

for i, j, k in indices:
    print ...

For example,

In [1]: x = np.random_integers(0, 1, (3, 3, 3))
In [2]: np.where(x) # you want np.where(x==0)
Out[2]: (array([0, 0, 0, 0, 0, 1, 1, 1, 1, 2]),
         array([0, 1, 1, 2, 2, 0, 0, 1, 1, 2]),
         array([1, 0, 1, 0, 1, 1, 2, 0, 2, 2]))
In [3]: zip(*np.where(x))
Out[3]: [(0, 0, 1),
         (0, 1, 0),
         (0, 1, 1),
         (0, 2, 0),
         (0, 2, 1),
         (1, 0, 1),
         (1, 0, 2),
         (1, 1, 0),
         (1, 1, 2),
         (2, 2, 2)]
like image 199
wflynny Avatar answered Oct 03 '22 10:10

wflynny