Aggregations & the axis argument

Does axis=0 mean "rows" or "columns"? The endlessly-confusing answer becomes obvious once you flip the question to: which axis am I collapsing away?

sum / mean / maxaxis=0 vs axis=1 reduction

The mental model that fixes it

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:

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:

axis=0 vs axis=1, decoded

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):

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.

Why you'll use this constantly

Reductions over an axis are the bread and butter of data work and ML preprocessing:

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.

Takeaways: 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.