Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

I want a function that behaves like enumerate, but on numpy arrays.

>>> list(enumerate("hello"))
[(0, "h"), (1, "e"), (2, "l"), (3, "l"), (4, "o")]

>>> for x, y, element in enumerate2(numpy.array([[i for i in "egg"] for j in range(3)])):
        print(x, y, element)

0 0 e
1 0 g
2 0 g
0 1 e
1 1 g
2 1 g
0 2 e
1 2 g
2 2 g

Currently I am using this function:

def enumerate2(np_array):
    for y, row in enumerate(np_array):
        for x, element in enumerate(row):
            yield (x, y, element)

Is there any better way to do this? E.g. an inbuilt function (I couldn't find any), or a different definition that is faster in some way.

share|improve this question

marked as duplicate by tom10, Jaime, DSM, sweeneyrod, alko Jan 8 '14 at 19:25

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3  
possible duplicate of Iterating over a numpy array or if you don't care about the ordering: stackoverflow.com/questions/971678/… –  tom10 Jan 8 '14 at 19:19

1 Answer 1

up vote 6 down vote accepted

You want np.ndenumerate:

>>> for (x, y), element in np.ndenumerate(np.array([[i for i in "egg"] for j in range(3)])):
...     print(x, y, element)
... 
(0L, 0L, 'e')
(0L, 1L, 'g')
(0L, 2L, 'g')
(1L, 0L, 'e')
(1L, 1L, 'g')
(1L, 2L, 'g')
(2L, 0L, 'e')
(2L, 1L, 'g')
(2L, 2L, 'g')
share|improve this answer
    
Thanks, I'll accept this when the n minutes are up. Guess I should've looked at other parts of the library than the array methods, I suppose this makes more sense. –  sweeneyrod Jan 8 '14 at 19:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.