Numpy - Iterating Over Arrays
NumPy provides flexible and efficient ways to iterate over arrays of any dimensionality. For a one-dimensional array, iterating is straightforward and similar to iterating over a Python list.
Let's understand with the help of an example:
import numpy as np
# Create a 1D array
arr = np.array([1, 2, 3, 4, 5])
# Iterate over the array
for ele in arr:
print(ele)
Output
1 2 3 4 5
Explanation:
- Each element of the array is accessed sequentially, making iteration simple and intuitive.
Let's explore various others ways to iterate over Arrays:
Table of Content
Iteration Over a Two-Dimensional Array
For multidimensional arrays, iteration is performed over the first axis by default. Each iteration yields a one-dimensional sub-array.
import numpy as np
# Create a 2D array
arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Iterate over rows
for row in arr_2d:
print(row)
Output
[1 2 3] [4 5 6] [7 8 9]
Explanation:
- arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) creates a 2D array with three rows and three columns.
- for row in arr_2d: loops through each row of the 2D array, treating it as a separate one-dimensional array.
For Element-Wise Iteration
To iterate over individual elements of a 2D array, the array can be flattened using the .flat attribute.
import numpy as np
arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
for element in arr_2d.flat:
print(element)
Output
1 2 3 4 5 6 7 8 9
Iterating Over Higher-Dimensional Arrays
Iteration is similar for arrays with more than two dimensions. In such cases, iteration occurs along the first axis by default.
import numpy as np
# Create a 3D array
arr_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
# Iterate over the 3D array
for sub_array in arr_3d:
print(sub_array)
Output
[[1 2] [3 4]] [[5 6] [7 8]]
Explanation:
- Each iteration returns a 2D sub-array from the 3D array.
Using nditer
The numpy.nditer object offers a various way to iterate over arrays. It allows iteration in different orders and provides better control over the iteration process.
import numpy as np
# Using nditer
arr = np.array([[1, 2], [3, 4]])
for element in np.nditer(arr):
print(element)
Output
1 2 3 4
We can also specify the order of iteration (row-major order 'C' or column-major order 'F'):
import numpy as np
arr = np.array([[1, 2], [3, 4]])
for element in np.nditer(arr, order='F'):
print(element)
Output
1 3 2 4
Using Enumerate
For multidimensional arrays, we can use enumerate to access both the index and value during iteration.
import numpy as np
# Create a 2D array
arr = np.array([[10, 20], [30, 40]])
# Enumerate through rows
for idx, row in enumerate(arr):
print(f"Row {idx}: {row}")
Output
Row 0: [10 20] Row 1: [30 40]
Using Broadcasting
When working with arrays of different shapes, Broadcasting allows iteration across combined shapes seamlessly.
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([[10], [20]])
# Perform a broadcasted addition
for x, y in np.nditer([arr1, arr2]):
print(f"{x} + {y} = {x + y}")
Output
1 + 10 = 11 2 + 10 = 12 3 + 10 = 13 1 + 20 = 21 2 + 20 = 22 3 + 20 = 23