Or reshape y
for i in y.reshape(-1,3):
print i
A double iteration also works:
for x in y:
for z in x:
print z
Plain nditer
iterates over each element of y
(nditer
does not give you the indices):
for i in np.nditer(y):
print i
# wrong y[i]
You'll need to dig more into the flags and documentation for nditer
to iterate over 2 of its dimensions. While nditer
gives access to the underlying iteration mechanism, you don't usually need to use it - unless you are doing something unusual, or trying to speed up code with cython
.
Here's an example of getting 2 values from iteration on an nditer
object. There is one value for each array in the op
list. Both x
and z
are ()
shape arrays.
for x,z in np.nditer([y,y]):
print x,z
There's more on the use of nditer
at
http://docs.scipy.org/doc/numpy/reference/arrays.nditer.html
This doc page has an example using external_loop
that dishes out the array in subarrays, rather than individually. I can accomplish the same with the 3d y
by reordering its axes:
y3=y.swapaxes(2,0).copy(order='C')
for i in np.nditer(y3,order='F',flags=['external_loop']):
print i,
[242 14 211] [198 7 0] [235 60 81] [164 64 236]
So we can use nditer
to do this shallow iteration, but is it worth it?
In Iterating over first d axes of numpy array, I stumbled upon ndindex
:
for i in np.ndindex(y.shape[:2]):
print y[i],
# [242 14 211] [198 7 0] [235 60 81] [164 64 236]
ndindex
uses nditer
. The trick to generating shallow iteration is to use a subarray using just the dimensions you want to iterate over.
class ndindex(object):
def __init__(self, *shape):
...
x = as_strided(_nx.zeros(1), shape=shape, strides=_nx.zeros_like(shape))
self._it = _nx.nditer(x, flags=['multi_index', 'zerosize_ok'], order='C')
def __next__(self):
next(self._it)
return self._it.multi_index
Or stripping out the essential parts of ndindex
I get:
xx = np.zeros(y.shape[:2])
it = np.nditer(xx,flags=['multi_index'])
while not it.finished:
print y[it.multi_index],
it.iternext()
# [242 14 211] [198 7 0] [235 60 81] [164 64 236]