axis argumentDoes axis=0 mean "rows" or "columns"? The endlessly-confusing answer becomes
obvious once you flip the question to: which axis am I collapsing away?
An aggregation (sum, mean, max, std, …) takes
many numbers and reduces them to fewer. The axis argument says which dimension to reduce
along — and the trick is that the axis you name is the one that disappears.
Picture a 2-D array as a grid with axis=0 running vertically (down the rows) and
axis=1 running horizontally (across the columns) — the same order as
.shape = (rows, cols). So:
axis=0 → travel down each column, combining all the rows → the row dimension
collapses → you get one number per column (a column-wise result).axis=1 → travel across each row, combining all the columns → the column dimension
collapses → you get one number per row (a row-wise result).The size rule makes it concrete: aggregating a (3, 4) array over axis=0 leaves
shape (4,) (rows gone); over axis=1 leaves (3,) (columns gone).
Pick an axis and operation below — the highlighted arrows show what's being combined, and the result
appears along the axis that survives:
The exam asks for np.sum([[1, 2], [3, 4]], axis=1) and axis=0 on the array
[[1, 2], [3, 4]] (click Load above to see it live):
axis=1 sums across each row → [1+2, 3+4] = [3, 7].axis=0 sums down each column → [1+3, 2+4] = [4, 6].1+2+3+4 = 10.If you ever blank on it mid-problem, fall back to the shape rule: a (2, 2) array summed
over axis=1 must come out shape (2,) — one number per row — so it has to be the
row sums.
Reductions over an axis are the bread and butter of data work and ML preprocessing:
(samples, features),
X.mean(axis=0) gives the mean of each feature — exactly what you subtract to
center data before standardizing (then broadcasting it back).X.sum(axis=1) totals each row — e.g. summing a one-hot or
a probability row.(N, H, W, C), axis=(1, 2)
averages over height & width to get a per-image, per-channel value. Same rule: the named axes vanish.Tip: pass keepdims=True when you want the collapsed axis to stay as size 1
(e.g. (3, 1) instead of (3,)) so the result broadcasts cleanly back against the
original — the usual move in a softmax.
axis=k is the dimension that collapses.
For a 2-D array: axis=0 reduces down the rows → one value per column;
axis=1 reduces across the columns → one value per row. When in doubt, reason from the
output shape (the named axis is removed). Use keepdims=True to keep it broadcastable.