There are many ways to iterate over a 2D array. Examples below.
Most of these approaches, while functional, strike me as difficult to read. Some are very memory-expensive, and most do not generalize well to N-dimensions.
Is there a more readable way, preferably one that is computationally efficient and generalizes to ND nicely, to iterate over all coordinate sets in an ndarray?
arr = np.arange(100).reshape([10,10])
x,y = np.indices(arr.shape)
for i,j in zip(x.flat,y.flat):
dosomething(arr[i,j])
for i,j in np.nditer(np.indices(arr.shape).tolist()):
dosomething(arr[i,j])
for i in xrange(arr.shape[0]):
for j in xrange(arr.shape[1]):
dosomething(arr[i,j])
for i,j in itertools.product(range(arr.shape[0], range.shape[1])):
dosomething(arr[i,j])
# on further thought, maybe this one is OK?
for ind in xrange(arr.size):
i,j = np.unravel_index(ind, arr.shape)
dosomething(arr[i,j])
for i,j in itertools.product(*map(xrange, arr.shape)):
dosomething(arr[i,j])
(the latter from Pythonic way of iterating over 3D array)
The question I really wanted an answer to was "how do I get the x
,y
indices of an array?" The answer is:
for i,j in (np.unravel_index(ind,arr.shape) for ind in xrange(arr.size)):
dosomething(arr[i,j])
(np.unravel_index(ind,arr.shape) for ind in xrange(arr.size))
is a fairly readable and efficient generator.
But, for the question asked in the title, the other (linked) answers are better (np.nditer
, np.enumerate
)