Many NumPy functions accept axis= to reduce or aggregate along rows, columns, or higher dimensions. Axis numbering starts at 0 for the outermost dimension.
2D axis cheat sheet
axis=0— down columns (result per column)axis=1— across rows (result per row)axis=None— flatten entire array first
Examples
import numpy as np
m = np.arange(12).reshape(3, 4)
print('col sums:', m.sum(axis=0))
print('row sums:', m.sum(axis=1))
keepdims
keepdims=True preserves reduced axes as length 1—helps broadcasting the result back against the original shape.
Important interview questions and answers
- Q: mean(axis=0) on 100×5 matrix?
A: Five values—one mean per column. - Q: Negative axis?
A: Counts from last dimension: axis=-1 is last axis.
Self-check
- Compute per-row max of a 2D array.
- What does keepdims=True do?
Tip: For 2D data: axis=0 down columns, axis=1 across rows.
Interview prep
- axis=0 on 2D?
Aggregate down columns—one result per column.
- keepdims?
Preserves reduced axes as length 1 for broadcasting back.