What is the Equivalent of Enum in NumPy?

Learn via video courses
Topics Covered

Enum is the class of the Python module. With the help of enums, enumerations in Python are created. Enumeration is the process of listing each item in a sequence individually. Enumerations in NumPy are the equivalent of an enum. When we need to have the index of the element while iterating, we use the enumerate() function. This method returns the pair of the location of an element in the memory, i.e., the index and value of the element. It is an iterator for a multidimensional index, as iterables are used for both the index and the element.

The following is the syntax for the enumerate function:

Syntax:

Parameters: array The parameter array is the input ndarray.

Let's look at the following examples to understand how to enumerate works in Numpy:

Iterating 1-D array

Code:

Output:

Explanation:

An array arr is created using the np.arange function. We iterate over an array with an iterable index and item using a for a loop. Using the np.ndenumerate() function on array arr we get pair of elements and their indices.

Iterating 2-D array

Code:

Output:

Explanation:

A 1-D array arr is created using the np.arange function and then transformed into a 2-D array using the np.reshape function and stored in arr1. Iterating over an array arr1 using index and item as iterables in for loop with np.ndenumerate, we get pairs of elements and their indices as output. Here we can see there are two values in the index, one for a row and the second one for a column element 1 is at the 0th row and 0th column, element 3 is at the 0th row and 1st column, and so on.

Iterating 3-D array

Code:

Output:

Explanation:

In the above code example, a 1-D array arr is created using the np.arange function and then transformed into 3-D using the np.reshape function. There are two planes in the above array, and inside the two planes, we have two arrays of shape(2x3), i.e. in each plane, we have an array of 2 rows and 3 columns. Using for loop with index and item as iterables with the np.ndenumerate function, we get pairs of elements and their indices as output. Here are three values in the index, 1st one is for the plane,2nd one is for the row, and 3rd one is for the column. such as Element 11 is presented at 1st plane 0th plane, 1st row, and 2nd column in an array and so on.

Conclusion

  • Enum is the class of Python used to create enumerations.
  • Enumeration in NumPy is equivalent to enums and can be created using the np.ndenumerate() function.
  • enumerators in Numpy are used when we want both index and value of the element at the same time.
  • we can iterate over 1-d,2-D, and 3-D arrays using a single loop and can get pairs of values and their indices.