Iterate over the output of `np.where`

I have a 3D array and use np.whereto search for elements that satisfy a certain condition. The output np.whereis a set of three 1D arrays, each of which gives indices along one axis. I would like to iterate over this conclusion and print out the index of each point in the matrix satisfying the condition.

One way to do this:

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

However, this looks a bit cumbersome, and I was wondering if there is a better way?

+3
source share
2 answers

Use zip

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

Then you can do

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

For instance,

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)]
+6
source

Use np.transposeover zip, it is faster for large arrays

import numpy as np
myarray = np.random.randint(0, 7, size=1000000)
%timeit indices = zip(*np.where(myarray == 0))
%timeit indices = np.transpose(np.where(myarray == 0))

10 loops, best of 3: 31.8 ms per loop
100 loops, best of 3: 15.9 ms per loop
+1
source

All Articles