In this tutorial you will learn:
Iterating Multi Dimensional Arrays
Iteration is the repetition of a process, incase of iteration of Array it can be termed as traversing each value of array one after another for either printing it or checking it against a certain condition. The most simplest way to iterate an array in NumPy is using a ‘For loop’. Using a for loop we can access each value of the array in a sequential order.
In this example there is a 1D array which we will be iterating using a For Loop
import numpy as np my_arr = np.array(['s','o','u','r','c','e']) print('1D Array which we will be iterating is: ',my_arr) print('The contents of 1D array are:') for z in my_arr: print(z, end=' ')
In this example I will use the For Loop method for iterating a 2D array. Here you can see that we are using 1 nested loop in order to access the second dimension of the array
import numpy as np my_arr = np.array([['s','o','u','r','c','e'],['c','o','d','e','s','t']]) print('2D Array which we will be iterating is:\n ',my_arr) print('The contents of 2D array are:') for z in my_arr: for y in z: print(y, end=' ')
In this example I will iterate a 3D array using a 3 For Loop. Here you can see that we will be using 2 nested For loops to access all the elements by iterating in all the dimensions.
import numpy as np my_arr = np.array([[['s','o','u','r','c','e'],['c','o','d','e','s','t'],['t','u','t','o','r','i']]]) print('3D Array which we will be iterating is:\n ',my_arr) print('The contents of 3D array are:') for z in my_arr: for y in z: for x in y: print(x, end=' ')
Iterating Arrays using ndenumerate()
NumPy ndenumerate is a multi dimensional index iterator and it returns an iterator yielding pair of array coordinates and values. The functionality of ndenumerate is same as that of nditer except the following three main differences.
In this example we are iterating a 2D array using denumerate, here you can see that indexes(coordinates) of the array along with the values at that specific index will be printed together
import numpy as np my_arr = np.array([['s','o','u','r','c','e'],['c','o','d','e','s','t']]) print('2D Array which we will be iterating is:\n ',my_arr) print('The result of iteration using ndenumerate are :') for i, z in np.ndenumerate(my_arr): print(i, z)
In this example we are iterating a 3D array using denumerate, here you can see that indexes(coordinates) of the array along with the values at that specific index will be printed together
import numpy as np my_arr = np.array([[['s','o','u','r','c','e'],['c','o','d','e','s','t'],['t','u','t','o','r','i']]]) print('3D Array which we will be iterating is:\n ',my_arr) print('The result of iteration using ndenumerate are :') for i, z in np.ndenumerate(my_arr): print(i, z)