Sub topic 10
Three Dimensions and Tuples of Axes
This chapter assumes you can create arrays with np.array, np.arange, and reshape, and that you can read an array's shape. It also assumes you already know how axis=0 and axis=1 work on a two-dimensional array. Here we extend that rule to three dimensions, then to several axes at once.
One rule that scales to any dimension
An array with n dimensions has axes numbered 0 to n - 1. Each axis number is a position in the shape tuple. For a shape of (2, 3, 4):
- Axis 0 has length 2.
- Axis 1 has length 3.
- Axis 2 has length 4.
A reduction such as sum with axis=k combines all the values along axis k into one value. Axis k then disappears from the result's shape. Every other axis stays in place, in the same order.
This is the same rule you used for two dimensions. A 2-D array of shape (2, 3) summed over axis=0 gives shape (3,). A 3-D array just has one more axis that can be removed or kept.
A concrete picture helps. Read the shape (2, 3, 4) as 2 blocks, each with 3 rows and 4 columns. A sales table might use weeks, stores, and products in that order.
Reducing one axis of a 3-D array
The following code reduces each of the three axes in turn.
import numpy as np
b = np.arange(24).reshape(2, 3, 4)
print(b.shape) # (2, 3, 4)
print(b.sum()) # 276
print(b.sum(axis=0))
# [[12 14 16 18]
# [20 22 24 26]
# [28 30 32 34]]
print(b.sum(axis=1))
# [[12 15 18 21]
# [48 51 54 57]]
print(b.sum(axis=2))
# [[ 6 22 38]
# [54 70 86]]Each result tells you what was combined:
axis=0adds the two blocks together, position by position. The shape(2, 3, 4)becomes(3, 4). Entry[j, k]of the result isb[0, j, k] + b[1, j, k].axis=1adds the three rows inside each block. The shape becomes(2, 4).axis=2adds the four values inside each row. The shape becomes(2, 3).
In general, result[j, k] for axis=0 equals the sum of b[i, j, k] over every i. You can write the same sentence for any axis by swapping which index varies.
Negative axis numbers count from the end. In a 3-D array, axis=-1 means axis=2, and axis=-3 means axis=0. Using -1 for "the last axis" keeps code correct when the number of leading dimensions changes.
import numpy as np
b = np.arange(24).reshape(2, 3, 4)
try:
b.sum(axis=3)
except ValueError as err:
print(err) # axis 3 is out of bounds for array of dimension 3An axis number outside -3 to 2 raises an AxisError, which is a subclass of ValueError. The usual cause is a mismatch between the array you think you have and the one you actually have. Print b.shape first.
Reducing several axes with a tuple
Pass a tuple to axis to reduce several axes in one call. NumPy removes every listed axis from the shape.
import numpy as np
b = np.arange(24).reshape(2, 3, 4)
print(b.sum(axis=(0, 2))) # [ 60 92 124]
print(b.sum(axis=(1, 2))) # [ 66 210]
print(b.sum(axis=(0, 1))) # [60 66 72 78]
print(b.sum(axis=(0, 1, 2))) # 276
print(b.sum(axis=-1).shape) # (2, 3)The axes you list are the ones that vanish. The axes you leave out survive, so the tuple names what you want to collapse, not what you want to keep. A quick way to read axis=(0, 2) is "one total per index of axis 1". The three results are the per-store totals over all weeks and products. The table lists the other combinations.
| Call on shape `(2, 3, 4)` | Axes removed | Result shape | Meaning if axes are weeks, stores, products |
|---|---|---|---|
| `b.sum(axis=(0, 1))` | 0, 1 | `(4,)` | Total per product |
| `b.sum(axis=(0, 2))` | 0, 2 | `(3,)` | Total per store |
| `b.sum(axis=(1, 2))` | 1, 2 | `(2,)` | Total per week |
| `b.sum(axis=(0, 1, 2))` | all | `()` | One grand total |
Reducing every axis gives a scalar, the same as calling b.sum() with no axis. The order inside the tuple does not matter, so (0, 2) and (2, 0) give the same result. Repeating an axis, as in (0, 0), raises a ValueError.
A tuple equals repeated single-axis reductions
Reducing (0, 2) at once gives the same numbers as reducing the axes one after another. There is one trap: after the first reduction, the remaining axes are renumbered.
import numpy as np
b = np.arange(24).reshape(2, 3, 4)
direct = b.sum(axis=(0, 2))
step_a = b.sum(axis=2).sum(axis=0) # remove 2 first, then 0
step_b = b.sum(axis=0).sum(axis=1) # remove 0 first, so old axis 2 is now axis 1
print(np.array_equal(direct, step_a)) # True
print(np.array_equal(direct, step_b)) # TrueIn step_b, summing over axis=0 leaves shape (3, 4). The old axis 2 is now axis 1. If you wrote .sum(axis=2) on that second step, you would get an error, because a 2-D array has no axis 2.
Prefer the tuple form. It avoids the renumbering, and it makes one pass over the data. With floating-point numbers, the order of additions can change the last digits of a result, so the stepwise form may differ from the tuple form by a tiny amount. For integers the results are identical.
Tuples with keepdims
A tuple works with keepdims=True. Every listed axis stays with length 1, so the result still has three dimensions and broadcasts against the original array.
import numpy as np
b = np.arange(24).reshape(2, 3, 4)
m = b.mean(axis=(0, 2), keepdims=True)
print(m.shape) # (1, 3, 1)
print(m.ravel()) # [ 7.5 11.5 15.5]
centered = b - m
print(centered.shape) # (2, 3, 4)
print(centered.mean(axis=(0, 2))) # [0. 0. 0.]This subtracts the mean of each store, taken over all weeks and products, from every value for that store. Shape (1, 3, 1) lines up against (2, 3, 4): the 1s stretch to 2 and 4, and the 3 matches the middle axis.
Without keepdims, the mean has shape (3,). Broadcasting aligns shapes from the right, so (3,) would be matched against the last axis of length 4, and b - b.mean(axis=(0, 2)) raises a ValueError. Worse, if the last axis also had length 3, the code would run and subtract the wrong thing. This is the most common silent bug with 3-D data.
Which functions accept a tuple
Not every function that takes axis accepts a tuple. The rule is about whether the function combines values into one number.
| Accepts a tuple of axes | Accepts only one integer axis |
|---|---|
| `sum`, `prod`, `mean`, `min`, `max`, `std`, `var`, `median`, `any`, `all`, `nansum`, `nanmean` | `argmax`, `argmin`, `cumsum`, `cumprod` |
argmax returns the position of a value along one axis, so "position along several axes at once" has no single answer. cumsum keeps the input shape and walks along a single line of values. Passing a tuple to either raises a TypeError.
To find the position of the largest value within each block, flatten the axes you want to search over, then apply argmax along the flattened axis. You can then convert the flat index back into row and column positions.
import numpy as np
b = np.arange(24).reshape(2, 3, 4)
flat = b.reshape(b.shape[0], -1) # shape (2, 12): one flat row per block
idx = flat.argmax(axis=1)
print(idx) # [11 11]
rows, cols = np.divmod(idx, b.shape[2])
print(rows, cols) # [2 2] [3 3]reshape(b.shape[0], -1) keeps axis 0 and merges the last two axes into one. The -1 tells NumPy to compute that length (12). np.divmod(idx, 4) splits each flat index into a row number and a column number within its block. Here the largest value sits at row 2, column 3 of each block, which is b[0, 2, 3] = 11 and b[1, 2, 3] = 23.
Checking a result before you trust it
Four checks catch most mistakes with three or more dimensions:
- Write down the shape before you call the function, for example
(weeks, stores, products). - Decide which axes should vanish and predict the result shape by deleting them from that tuple.
- Compare your prediction with
result.shape. - Spot-check one value by hand, using ordinary indexing. For example,
b[:, 1, :].sum()should equalb.sum(axis=(0, 2))[1], which is 92.
Exercise
An array s has shape (5, 4, 3, 2). What is the shape of s.sum(axis=(1, 3)), and what is the shape of s.mean(axis=(1, 3), keepdims=True)?
Show answer
Deleting axes 1 and 3 from (5, 4, 3, 2) leaves (5, 3). With keepdims=True the removed axes stay with length 1, so the shape is (5, 1, 3, 1).
Exercise
Using b = np.arange(24).reshape(2, 3, 4), write one expression that divides every value by the total of its own block (axis 0 index), so that each block sums to 1. Then state the shape of the divisor.
Show answer
shares = b / b.sum(axis=(1, 2), keepdims=True). The divisor has shape (2, 1, 1), which broadcasts against (2, 3, 4). Each block shares[i] then sums to 1.0. The block totals are 66 and 210.
Exercise
Why does b.argmax(axis=(0, 2)) fail, and how do you find the flat position of the maximum within each block along axis 0?
Show answer
argmax accepts only a single integer axis, so a tuple raises a TypeError. Merge the axes you want to search with b.reshape(b.shape[0], -1) and call argmax(axis=1) on the result. You can then convert the flat indices to row and column positions with np.divmod(idx, b.shape[2]).