Search code examples
pythonmatrixnumpyenumerate

Iterate over numpy matrix of unknown dimension


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?


Solution

  • 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)]