Sub topic 3
Reductions, Reshaping, and Efficient NumPy Arrays
Assume you know basic Python and understand array shapes, indexing, and dtypes. NumPy reductions combine values along an axis. For a 2-D array, axis=0 collapses rows and axis=1 collapses columns.
Reductions along an axis
import numpy as np
m = np.array([[1, 2, 3], [4, 5, 6]])
print(m.sum(axis=0)) # [5 7 9]
print(m.mean(axis=1)) # [2. 5.]
print(m.max(axis=1, keepdims=True)) # [[3]
# [6]]keepdims=True keeps the reduced dimension with length one. This makes the result easier to broadcast back over the original array.
Reshaping and transposing
reshape changes the shape without changing the element order. The inferred dimension -1 lets NumPy calculate that dimension.
a = np.arange(6).reshape(2, 3)
print(a.T.shape) # (3, 2)
print(a.reshape(3, -1))A transpose changes axis order. It often returns a view rather than copying data.
Concatenating and stacking
concatenate joins arrays along an existing axis. stack creates a new axis.
| Operation | Result shape for two arrays of shape `(2, 3)` |
|---|---|
| `np.concatenate([a, a], axis=0)` | `(4, 3)` |
| `np.stack([a, a])` | `(2, 2, 3)` |
Matrix multiplication with `@`
Use @ for matrix multiplication. Use * for elementwise multiplication. For A @ B, the inner dimensions must match.
A = np.array([[1, 2], [3, 4]])
B = np.array([[0, 1], [1, 0]])
print(A @ B)
print(A * B)Random arrays with `default_rng`
Create a Generator for modern random-number generation. A seed makes results repeatable during testing.
rng = np.random.default_rng(42)
samples = rng.normal(0, 1, size=(2, 3))
print(samples.shape)Memory layout and strides
A stride is the number of bytes NumPy moves to reach the next element along an axis. Transposing commonly swaps strides without copying the data.
a = np.arange(6, dtype=np.int64).reshape(2, 3)
print(a.strides) # commonly (24, 8)
print(a.T.strides) # commonly (8, 24)Performance tips and common pitfalls
- Prefer vectorized expressions such as
a * 2over Python loops. - Check shapes before matrix multiplication and broadcasting.
- Remember that integer casting can truncate values.
- Non-contiguous views, such as transposes, can be slower for some operations.
- Use boolean masks for selection, but expect advanced indexing to create a copy.
Exercise
For an array x with shape (4, 3), which expression computes the mean of each column while preserving a broadcastable shape?
Show answer
x.mean(axis=0, keepdims=True), which returns shape (1, 3).