Sub topic 3
Choosing a direction with axis
This chapter assumes you can create arrays with np.array and np.arange, read an array's shape, and index a two-dimensional array with a[row, column]. It covers how the axis argument selects the direction of a reduction, how to predict what disappears from the shape, and which errors to expect when axis is wrong.
What the argument controls
A reduction such as sum combines many values into one. For a whole array there is only one way to do that: combine everything. For an array with two or more dimensions there are several, because you can combine values along any one of the dimensions. The axis argument names which dimension to combine along.
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]The array has shape (2, 3). Axis 0 has length 2 and axis 1 has length 3. The axes are numbered in the same order as the entries of shape, starting at 0.
The rule: the named axis disappears
Remember one rule: the axis you name is the one that is collapsed, and it is removed from the shape. Every other axis stays.
axis=0collapses axis 0, which has length 2. The result has shape(3,): one value per column.axis=1collapses axis 1, which has length 3. The result has shape(2,): one value per row.
You can check the rule by writing out what NumPy does. For axis=0, it adds up the slices you get by fixing the first index.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
by_axis0 = a.sum(axis=0)
by_hand0 = a[0] + a[1] # slices along axis 0
print(np.array_equal(by_axis0, by_hand0)) # True
by_axis1 = a.sum(axis=1)
by_hand1 = a[:, 0] + a[:, 1] + a[:, 2] # slices along axis 1
print(np.array_equal(by_axis1, by_hand1)) # TrueIn both cases the sum runs over the index of the axis you named. The other index is left alone, so each position in the result gets its own total.
"Rows" and "columns" are easy to mix up
People often say that axis=0 means rows and axis=1 means columns. That wording is ambiguous. With axis=0 you do work down the rows, yet the result has one entry per column. Two descriptions that avoid the confusion:
axis=0combines values down each column, so you get column totals.axis=1combines values across each row, so you get row totals.
If you only remember the shape rule, you can always rebuild the answer: delete the named axis from the shape, and what remains is the shape of the result.
| Call on shape `(2, 3)` | Axis collapsed | Result shape | Meaning |
|---|---|---|---|
| `a.sum()` | all of them | `()` (a scalar) | one total for the whole array |
| `a.sum(axis=0)` | 0 | `(3,)` | one total per column |
| `a.sum(axis=1)` | 1 | `(2,)` | one total per row |
A second example with different lengths on each axis makes the rule easier to see.
import numpy as np
m = np.arange(12).reshape(3, 4)
print(m)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
print(m.sum(axis=0)) # [12 15 18 21]
print(m.sum(axis=0).shape) # (4,)
print(m.sum(axis=1)) # [ 6 22 38]
print(m.sum(axis=1).shape) # (3,)The array has shape (3, 4). Removing axis 0 leaves (4,), which is the four column totals. Removing axis 1 leaves (3,), which is the three row totals.
Three ways to write the same call
axis works the same way in the method form and in the function form. It can be passed by keyword or by position.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(a.sum(axis=0)) # [5 7 9]
print(np.sum(a, axis=0)) # [5 7 9]
print(a.sum(0)) # [5 7 9]Prefer the keyword form. a.sum(0) is easy to misread as "sum something called 0". Some functions also have other positional arguments before or after axis, so naming it avoids passing a value to the wrong parameter.
The same argument exists on max, min, mean, std, prod, any, all, argmax, and argmin. Later chapters use it with those functions. Functions that do not reduce also take axis, but they use it to choose a direction rather than to remove it. For example, np.sort(a, axis=1) sorts within each row and keeps the shape.
Negative axes
A negative axis counts from the end of the shape. -1 is the last axis, -2 is the second to last, and so on.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(a.sum(axis=-1)) # [ 6 15] same as axis=1
print(a.sum(axis=-2)) # [5 7 9] same as axis=0Negative axes are useful when you write code that must work for arrays with a varying number of dimensions. For example, "reduce the last axis" is axis=-1 whether the array has two dimensions or five. Using axis=1 in that code would silently reduce the wrong axis once the array gets a new leading dimension.
axis=None and the default
axis=None is the default for the reductions in this chapter. It means "treat the whole array as one collection," so you get a single scalar back.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(a.sum(axis=None)) # 21
print(a.sum()) # 21
print(a.sum(axis=(0, 1))) # 21The third call passes a tuple that names every axis. It gives the same result as None, because collapsing all the axes leaves nothing but a scalar. Tuples of axes are covered properly in the chapter on three-dimensional arrays. For now, note that axis can also take a tuple.
Errors from a wrong axis
An axis number must be smaller than the number of dimensions. Asking for an axis that does not exist raises an error.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
try:
a.sum(axis=2)
except ValueError as err:
print(type(err).__name__) # AxisError
print(err) # axis 2 is out of bounds for array of dimension 2AxisError inherits from both ValueError and IndexError, so catching ValueError works across NumPy versions. In recent releases the class lives in numpy.exceptions. In older ones it is numpy.AxisError.
The dangerous mistakes are the ones that do not raise an error. Two are common:
- Choosing the wrong axis on a square array. A
(3, 3)array accepts bothaxis=0andaxis=1, and both give a result of shape(3,). The result has the right shape but the wrong meaning, and nothing flags it. - Combining a reduced result with the original array. The reduced shape often no longer lines up with the original, as the next example shows.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
row_totals = a.sum(axis=1)
print(row_totals.shape) # (2,)
try:
a / row_totals
except ValueError as err:
print(err)
# operands could not be broadcast together with shapes (2,3) (2,)The result has shape (2,), and NumPy lines it up against the last axis of a, which has length 3. They do not match. If a had been (2, 2), the division would have run and given wrong numbers. The next chapters on result shapes and keepdims show how to fix this.
A quick way to check your choice
Before you run a reduction, answer two questions.
- Which axis do I want to disappear? That is the
axisvalue. - What shape do I expect afterwards? Delete that axis from the shape.
Then compare against result.shape after the call. If the two disagree, the axis is wrong. This takes a few seconds and catches most mistakes.
Summary of the rules
axisis the position of an entry inshape, counted from 0.- The named axis is collapsed and removed. All other axes remain, in order.
axis=0gives column totals on a 2D array.axis=1gives row totals.- Negative values count from the end.
axis=-1is always the last axis. axis=None, the default, reduces the whole array to a scalar.- An axis number at or above the number of dimensions raises
AxisError.
Exercise
An array m has shape (3, 4). You want one value per row, so you need a result of shape (3,). Which call do you use: m.sum(axis=0) or m.sum(axis=1)? Also give the equivalent call that uses a negative axis.
Show answer
Use m.sum(axis=1). Axis 1 has length 4 and is removed, which leaves the shape (3,) with one total per row. The negative form is m.sum(axis=-1), because -1 refers to the last axis, which is axis 1 for a 2D array.
Exercise
What does np.arange(6).reshape(2, 3).sum(axis=0) return, and what is its shape?
Show answer
The array is [[0, 1, 2], [3, 4, 5]]. Collapsing axis 0 adds the two rows, so the result is [3 5 7] with shape (3,).