4

I have a multidimensional numpy array I'd like to iterate over. I want to be able to access not only the values, but also their indices. Unfortunately,

for idx,val in enumerate(my_array):

doesn't seem to work when my_array is multidimensional. (I'd like idx to be a tuple). Nested for loops might work, but I don't know the number of dimensions of the array until runtime, and I know it's not appropriate for python anyway. I can think of a number of ways to do this (recursion, liberal use of the % operator), but none of these seem very 'python-esque'. Is there a simple way?

user1558954
  • 43
  • 1
  • 3
  • `enumerate` always returns an integer for the first value. What specifically are you expecting idx to contain? – ashastral Jul 28 '12 at 00:48

1 Answers1

10

I think you want ndenumerate:

>>> import numpy
>>> a = numpy.arange(6).reshape(1,2,3)
>>> a
array([[[0, 1, 2],
        [3, 4, 5]]])
>>> list(numpy.ndenumerate(a))
[((0, 0, 0), 0), ((0, 0, 1), 1), ((0, 0, 2), 2), ((0, 1, 0), 3), ((0, 1, 1), 4), ((0, 1, 2), 5)]
DSM
  • 342,061
  • 65
  • 592
  • 494