In a 3-D array, it will iterate through all the 2-D arrays.
Iterate through the elements of the following 3-D array:
import numpy as np arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]) for x in arr: print(x) |
To retrieve the actual values, or scalars, we need to iterate through the arrays in each dimension.
Iterate down to the scalar values:
import numpy as np arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]) for x in arr: for y in x: for z in y: print(z) |
The nditer() function is a utility that can be utilized for both basic and advanced iterations. It addresses some common challenges encountered during iteration; let’s explore it through examples.
In basic for loops, iterating through each scalar of an array requires using multiple nested loops (n loops), which can be challenging to write for arrays with high dimensionality.
Iterate through the elements of the following 3-D array:
import numpy as np arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) for x in np.nditer(arr): print(x) |
We can utilize the op_dtypes argument and specify the expected data type to change the data type of elements during iteration.
NumPy does not modify the element’s data type in place (within the original array); instead, it requires additional space to perform this action. This extra space is referred to as a buffer, and to enable it in nditer(), we pass flags=[‘buffered’].
Iterate through the array as if it were a string:
import numpy as np arr = np.array([1, 2, 3]) for x in np.nditer(arr, flags=[‘buffered’], op_dtypes=[‘S’]): print(x) |