NumPy Array Iterating
Iterating means visiting elements one by one with a for loop. A plain loop over an array walks along its first axis: for a 1-D array you get elements, for a 2-D array you get rows.
import numpy as np
steps = np.array([4200, 8100, 6500])
for s in steps:
print(s)
week = np.array([[1, 2, 3],
[4, 5, 6]])
for row in week:
print("row:", row)4200
8100
6500
row: [1 2 3]
row: [4 5 6]
To reach individual values of a 2-D array with plain loops you nest one loop per dimension:
import numpy as np
week = np.array([[1, 2, 3],
[4, 5, 6]])
for row in week:
for value in row:
print(value, end=" ")
print()1 2 3 4 5 6
That gets tedious for 3-D or 4-D data. NumPy has better tools.
np.nditer: every element, any dimension
np.nditer(a) yields each element in turn, no matter how many dimensions a has:
import numpy as np
cube = np.arange(8).reshape(2, 2, 2)
for x in np.nditer(cube):
print(x, end=" ")
print()0 1 2 3 4 5 6 7
nditer has options for advanced use. Two helpful ones: op_dtypes with flags=["buffered"] converts on the fly, and slicing the input lets you skip elements:
import numpy as np
a = np.array([[1, 2, 3, 4],
[5, 6, 7, 8]])
# Every second column, viewed as floats
for x in np.nditer(a[:, ::2], flags=["buffered"], op_dtypes=["float64"]):
print(x, end=" ")
print()1.0 3.0 5.0 7.0
Knowing where you are: np.ndenumerate
Python's enumerate gives a counter; NumPy's np.ndenumerate gives the full index tuple of each element:
import numpy as np
# Free seats in a tiny cinema: 1 = free
seats = np.array([[0, 1, 0],
[1, 1, 0]])
for (row, col), free in np.ndenumerate(seats):
if free:
print(f"Row {row}, seat {col} is free")Row 0, seat 1 is free
Row 1, seat 0 is free
Row 1, seat 1 is free
Iterating over columns
Looping over a.T (the transpose) visits the columns, because the transpose turns columns into rows:
import numpy as np
scores = np.array([[70, 80, 90],
[60, 75, 95]])
for i, column in enumerate(scores.T):
print(f"test {i}: {column}, best {column.max()}")test 0: [70 60], best 70
test 1: [80 75], best 80
test 2: [90 95], best 95
Should you iterate at all?
Loops in Python run one element at a time in the interpreter, which is far slower than NumPy's built-in operations. Most of the time you can replace a loop with a vectorised expression:
| Loop version | Vectorised version |
|---|---|
[x * 2 for x in a] |
a * 2 |
sum(x for x in a if x > 0) |
a[a > 0].sum() |
| loop that tracks max per column | a.max(axis=0) |
Tip: Use loops for small arrays, for printing, or when each step depends on the previous one. For calculations on whole arrays, reach for vectorised operations first. The Performance and Vectorization lesson measures the difference.
Test yourself
What does for x in a: yield when a is 2-D?
- Individual elements
- Rows
- Columns
- Index tuples
Which function yields (index_tuple, value) pairs?
- np.nditer
- np.ndenumerate
- enumerate
- np.ndindex
How can you loop over the columns of a 2-D array a?
- for c in a:
- for c in a.T:
- for c in a.flat:
- for c in a.shape: