Enumerating Python through a 2D array in numpy

I need 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 

I am currently 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 a better way to do this? For example. built-in function (I could not find it) or another definition that is somehow accelerated.

+7
python arrays numpy enumerate
source share
1 answer

Do 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') 
+13
source share

All Articles