import numpy as np
Iterating Over NumPy ArraysΒΆ
While vectorized operations should be your first choice for performance, sometimes you need to iterate through array elements β for example, when applying complex conditional logic that cannot be easily vectorized. For 1D arrays, a simple for loop works. For multi-dimensional arrays, you need nested loops (one per dimension), which quickly becomes cumbersome. NumPyβs np.nditer() function provides a flat iterator that traverses all elements regardless of dimensionality, eliminating the need for nested loops. However, remember that explicit iteration in Python is slow compared to vectorized operations, so use nditer() for inspection and debugging rather than heavy computation.
Iterating a 1-D ArrayΒΆ
For a 1D array, a standard for loop visits each element in order. The loop variable takes on the value of each element directly.
Iterating 2-D and 3-D ArraysΒΆ
For a 2D array, a single for loop iterates over rows (not individual elements). To reach each element, you need a nested loop. For 3D arrays, you need three levels of nesting. This escalating complexity is exactly why np.nditer() exists β it flattens the iteration regardless of how many dimensions the array has.
np2 = np.array([[1,2,3,4,5],[6,7,8,9,10]])
'''
for x in np2:
#print(x)
for y in x:
print(y)
'''
# 3-d
np3 = np.array([[[1,2,3],[4,5,6]], [[7,8,9], [10,11,12]]])
'''
for x in np3:
#print(x)
for y in x:
#print(y)
for z in y:
print(z)
'''
# np.nditer()
for x in np.nditer(np2):
print(x)