Sub topic 15
Using NumPy for 2D numeric data
This chapter assumes you can build and index nested lists, traverse them with nested loops, and know what transpose and matrix multiplication do. Here you will see how NumPy handles the same operations on 2D numeric data, and when to choose it over nested lists.
Why use a numeric array library
A nested list stores references to Python objects. Each row is a separate list, and each number is a separate object. That gives you flexibility, such as jagged rows and mixed types, but it costs memory and speed.
NumPy's ndarray stores numbers of one type in a single block of memory. This is the row-major layout from the memory layout chapter. Loops over the data run in compiled code instead of in the Python interpreter, so operations on whole arrays are much faster than the equivalent nested loops.
Shape, transpose, and sums
An array has a shape attribute, a tuple of (rows, columns). The .T attribute gives the transpose, and sum(axis=...) aggregates along one dimension.
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.shape) # (2, 3)
print(a.T.shape) # (3, 2)
print(a.sum(axis=0)) # [5 7 9]
print(a.sum(axis=1)) # [ 6 15]
print(a[1, 2]) # 6The axis argument names the dimension that gets collapsed. axis=0 collapses the rows, so you get one sum per column. axis=1 collapses the columns, so you get one sum per row.
Indexing uses one bracket pair with a comma, a[1, 2], instead of grid[1][2].
Whole-array arithmetic
Addition and scalar multiplication need no loops. The * operator multiplies element by element. It does not perform matrix multiplication.
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
print(a + b) # [[ 6 8]
# [10 12]]
print(a * 10) # [[10 20]
# [30 40]]
print(a * b) # [[ 5 12]
# [21 32]] element-wise, not matrix product
print(a @ b) # [[19 22]
# [43 50]] matrix productThe @ operator gives the same result as the three-loop matmul function you wrote earlier, but it runs in optimized compiled code.
Common errors
- Using
*for matrix multiplication. It multiplies element by element and gives a valid-looking but wrong result. Use@. - Mismatched shapes.
a @ bneeds the columns ofato equal the rows ofb. Otherwise NumPy raises aValueError. - Expecting jagged rows.
np.array([[1, 2], [3]])raises an error in current NumPy versions, because an array must be rectangular. Use a nested list for jagged data. - Integer overflow. An array has a fixed element type, such as
int64orfloat64. Python integers never overflow, but array elements can.
Choosing between the two
| Situation | Better choice |
|---|---|
| Large grids of numbers, matrix math, aggregates | NumPy |
| Rows of different lengths | Nested lists |
| Mixed types, such as strings and numbers | Nested lists |
| Small grids, no extra dependency wanted | Nested lists |
Writing the loops yourself still matters. It shows what NumPy does internally, and the loop-based bounds checking for grid neighbors has no direct NumPy shortcut.
Exercise
A NumPy array m has shape (4, 5). What is the shape of m.sum(axis=1), and what does each value in it represent?
Show answer
The shape is (4,). axis=1 collapses the columns, so each value is the sum of one row, giving one value for each of the 4 rows.
Exercise
You run a * b on two 2x2 arrays expecting the matrix product. Why is the result wrong, and what should you write instead?
Show answer
* multiplies matching elements, so each result cell is a[i][j] * b[i][j]. The matrix product needs a @ b.