NumPy: Enumerated Iteration Using ndenumerate()

Enumerated Iteration is used to mention the sequence number of the given elements in the sequence one by one. 

When we want the corresponding index of elements while iterating, we can use the ndenumerate() method. This method returns an iterator yielding pairs of array coordinates and values. It is multidimensional index iterator.

Example:

For 1-D Array:

import numpy as np
a=np.array(['a','b','c'])
for index, x in np.ndenumerate(a):
    print(index, x)

Output:

(0,) a
(1,) b
(2,) c

For 2-D Array:

import numpy as np
a=np.array([['a','b','c'],['d','e','f']])
for index, x in np.ndenumerate(a):
    print(index, x)

Output:

(0, 0) a
(0, 1) b
(0, 2) c
(1, 0) d
(1, 1) e
(1, 2) f
Thu, 09/09/2021 - 17:32

Authored by

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.