Introduction
Iterating over arrays is a common operation in data processing and manipulation. NumPy provides several efficient ways to iterate over arrays, leveraging its powerful broadcasting and vectorized operations. In this chapter, you will learn different methods for iterating over NumPy arrays.
Creating a NumPy Array
Before we begin iterating, let’s create a sample NumPy array.
import numpy as np
# Create a sample 2D NumPy array
array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("Array:\n", array)
Output:
Array:
[[1 2 3]
[4 5 6]
[7 8 9]]
Basic Iteration
Iterating Over a 1D Array
# Create a 1D NumPy array
array_1d = np.array([1, 2, 3, 4, 5])
# Iterate over the 1D array
for element in array_1d:
print(element)
Output:
1
2
3
4
5
Iterating Over a 2D Array
# Iterate over the 2D array row-wise
for row in array:
print("Row:", row)
Output:
Row: [1 2 3]
Row: [4 5 6]
Row: [7 8 9]
Iterating with nditer
The nditer
function provides a flexible way to iterate over multi-dimensional arrays.
Example: Using nditer
# Iterate over each element using nditer
for element in np.nditer(array):
print(element)
Output:
1
2
3
4
5
6
7
8
9
Modifying Array Elements
You can modify array elements in-place using nditer
with the op_flags
parameter.
Example: Modifying Elements
# Iterate and modify elements
for element in np.nditer(array, op_flags=['readwrite']):
element[...] = element * 2
print("Modified Array:\n", array)
Output:
Modified Array:
[[ 2 4 6]
[ 8 10 12]
[14 16 18]]
Iterating with Indices
You can iterate over arrays with access to both the elements and their indices using ndenumerate
.
Example: Using ndenumerate
# Iterate with indices using ndenumerate
for index, element in np.ndenumerate(array):
print("Index:", index, "Value:", element)
Output:
Index: (0, 0) Value: 2
Index: (0, 1) Value: 4
Index: (0, 2) Value: 6
Index: (1, 0) Value: 8
Index: (1, 1) Value: 10
Index: (1, 2) Value: 12
Index: (2, 0) Value: 14
Index: (2, 1) Value: 16
Index: (2, 2) Value: 18
Broadcasting Iteration
NumPy’s broadcasting rules allow you to iterate over arrays of different shapes together.
Example: Broadcasting Iteration
# Create another array for broadcasting
array_b = np.array([1, 0, 1])
# Iterate with broadcasting
for x, y in np.nditer([array, array_b]):
print(f"{x} + {y} = {x + y}")
Output:
2 + 1 = 3
4 + 0 = 4
6 + 1 = 7
8 + 1 = 9
10 + 0 = 10
12 + 1 = 13
14 + 1 = 15
16 + 0 = 16
18 + 1 = 19
Iterating with Multi-Index
For more complex multi-dimensional arrays, you can use ndindex
.
Example: Using ndindex
# Iterate with multi-index using ndindex
for index in np.ndindex(array.shape):
print("Index:", index, "Value:", array[index])
Output:
Index: (0, 0) Value: 2
Index: (0, 1) Value: 4
Index: (0, 2) Value: 6
Index: (1, 0) Value: 8
Index: (1, 1) Value: 10
Index: (1, 2) Value: 12
Index: (2, 0) Value: 14
Index: (2, 1) Value: 16
Index: (2, 2) Value: 18
Complete Example
Here is a complete example demonstrating various ways to iterate over NumPy arrays.
import numpy as np
# Create a sample 2D NumPy array
array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("Array:\n", array)
# Basic iteration over 1D array
array_1d = np.array([1, 2, 3, 4, 5])
for element in array_1d:
print(element)
# Basic iteration over 2D array
for row in array:
print("Row:", row)
# Iteration using nditer
for element in np.nditer(array):
print(element)
# Modifying elements using nditer
for element in np.nditer(array, op_flags=['readwrite']):
element[...] = element * 2
print("Modified Array:\n", array)
# Iteration with indices using ndenumerate
for index, element in np.ndenumerate(array):
print("Index:", index, "Value:", element)
# Broadcasting iteration
array_b = np.array([1, 0, 1])
for x, y in np.nditer([array, array_b]):
print(f"{x} + {y} = {x + y}")
# Iteration with multi-index using ndindex
for index in np.ndindex(array.shape):
print("Index:", index, "Value:", array[index])
Output:
Array:
[[1 2 3]
[4 5 6]
[7 8 9]]
1
2
3
4
5
Row: [1 2 3]
Row: [4 5 6]
Row: [7 8 9]
1
2
3
4
5
6
7
8
9
Modified Array:
[[ 2 4 6]
[ 8 10 12]
[14 16 18]]
Index: (0, 0) Value: 2
Index: (0, 1) Value: 4
Index: (0, 2) Value: 6
Index: (1, 0) Value: 8
Index: (1, 1) Value: 10
Index: (1, 2) Value: 12
Index: (2, 0) Value: 14
Index: (2, 1) Value: 16
Index: (2, 2) Value: 18
2 + 1 = 3
4 + 0 = 4
6 + 1 = 7
8 + 1 = 9
10 + 0 = 10
12 + 1 = 13
14 + 1 = 15
16 + 0 = 16
18 + 1 = 19
Index: (0, 0) Value: 2
Index: (0, 1) Value: 4
Index: (0, 2) Value: 6
Index: (1, 0) Value: 8
Index: (1, 1) Value: 10
Index: (1, 2) Value: 12
Index: (2, 0) Value: 14
Index: (2, 1) Value: 16
Index: (2, 2) Value: 18
Conclusion
Iterating over NumPy arrays can be done in several efficient ways using built-in functions like nditer
, ndenumerate
, and ndindex
. These methods provide flexibility and performance, allowing you to handle complex data processing tasks with ease.