Sub topic 4
Column totals and row totals
This chapter assumes you can create arrays with np.array and np.arange, and that you can read an array's shape. It covers how axis picks the direction of a reduction in a two-dimensional array, and how to check the result.
The two directions
A 2D array has two axes. Axis 0 runs down the rows, so it indexes the rows. Axis 1 runs across the columns, so it indexes the columns.
When you pass axis=n to an aggregation, NumPy collapses that axis. The values along it are combined into one value, and the axis disappears from the result.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(a.shape) # (2, 3)
print(a.sum()) # 21
print(a.sum(axis=0)) # [5 7 9]
print(a.sum(axis=1)) # [ 6 15]With no axis, the sum covers the whole array and returns one number. With axis=0, the two rows collapse, so you get one total per column. With axis=1, the three columns collapse, so you get one total per row.
A way to remember it
"Column totals" is the name for axis=0, but the name can mislead you. The axis you pass is the one that vanishes, not the one that remains. Ask "which axis do I want to get rid of?" The remaining axis keeps its length.
| Call | Axis removed | Result shape | Meaning |
|---|---|---|---|
| `a.sum(axis=0)` | 0 (rows) | `(3,)` | one total per column |
| `a.sum(axis=1)` | 1 (columns) | `(2,)` | one total per row |
The shape rule is the quickest check. The result shape is the input shape with the chosen axis deleted. For (2, 3) with axis=0, deleting the first entry leaves (3,).
Other aggregations follow the same rule
max, min, and mean use the same convention. Only the combining operation changes.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(a.max(axis=0)) # [4 5 6]
print(a.min(axis=1)) # [1 4]
print(a.mean(axis=0)) # [2.5 3.5 4.5]
print(a.sum(axis=1).shape) # (2,)Read a.max(axis=0) as "for each column, the largest value from top to bottom". Read a.min(axis=1) as "for each row, the smallest value from left to right".
Note that mean returns floats even when the input holds integers. The sum of integers stays an integer, but an average rarely is.
Common errors
- Mixing up the direction. Programmers often expect
axis=0to give row totals because it "sums rows". It sums down the rows, which produces column totals. Check the output shape to confirm. - Passing an axis that does not exist. For a 2D array,
a.sum(axis=2)raisesAxisError, because only axes 0 and 1 exist. - Expecting the result to keep two dimensions. After
a.sum(axis=1)you get shape(2,), not(2, 1). Code that assumes a 2D result will fail or give wrong values.
A short habit helps. Before you run an aggregation, write down the expected shape. Then compare it with result.shape.
import numpy as np
a = np.arange(12).reshape(3, 4)
col_totals = a.sum(axis=0)
row_totals = a.sum(axis=1)
print(col_totals, col_totals.shape) # [12 15 18 21] (4,)
print(row_totals, row_totals.shape) # [ 6 22 38] (3,)Here the array has 3 rows and 4 columns. Removing axis 0 leaves 4 values, one per column. Removing axis 1 leaves 3 values, one per row.
Exercise
The array m = np.arange(20).reshape(4, 5) has shape (4, 5). What shape does m.sum(axis=0) have, and what shape does m.mean(axis=1) have? Which one gives one value per row?
Show answer
m.sum(axis=0) has shape (5,), because axis 0 is removed and the 5 columns remain, giving one total per column. m.mean(axis=1) has shape (4,), because axis 1 is removed and the 4 rows remain. The second call, m.mean(axis=1), gives one value per row.
Exercise
A 2D array scores has one row per student and one column per exam. Which call gives each student's highest score: scores.max(axis=0) or scores.max(axis=1)?
Show answer
scores.max(axis=1). Axis 1 runs across the exams, so collapsing it leaves one maximum per student (per row).