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?
If you do this, Numpy where will simply output the index positions of the elements for which condition is True .
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.
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.
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With