Sub topic 1
Array shape and what an axis is
NumPy's axis argument only makes sense once you can read an array's shape without effort. This chapter builds that skill. You will learn what shape, ndim, and size report, how each position in the shape tuple is an axis, and how to find the line of values that an axis runs along. Later chapters use this to explain sum, mean, max, and the rest.
Prerequisites
This chapter assumes you can do the following:
- Write basic Python: variables, tuples,
print, andimport. - Create arrays with
np.arrayandnp.arange, and callreshape. - Index a list or a one-dimensional array with
x[i]and slice it withx[i:j].
You do not need to know anything about aggregation functions yet. If a[0, 1] looks unfamiliar, review two-dimensional indexing first. This chapter uses it heavily.
What shape tells you
Every NumPy array has a shape, a tuple of integers. Each integer is the length of the array along one dimension. The tuple's length is the number of dimensions, which NumPy reports as ndim.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(a.shape) # (2, 3)
print(a.ndim) # 2
print(a.size) # 6
print(a.dtype) # int64 on most platformsThe shape (2, 3) means the array has 2 rows and 3 columns. Three facts follow directly from the shape:
ndimequalslen(a.shape).sizeis the product of the shape entries, here 2 × 3 = 6.- The first number counts rows only because we conventionally print two-dimensional arrays as a table. NumPy itself only knows "the first dimension" and "the second dimension".
The last point matters. NumPy does not know about rows and columns. It knows positions in a shape tuple, and those positions are the axes.
What an axis is
An axis is one dimension of an array, identified by its position in the shape tuple, counting from zero.
| Shape entry | Axis number | Negative form | In a 2-D table |
|---|---|---|---|
| `2` (first) | `axis=0` | `axis=-2` | rows, running downward |
| `3` (second) | `axis=1` | `axis=-1` | columns, running across |
Axis 0 is the first index in a[i, j], and axis 1 is the second. The length of axis 0 is a.shape[0], and the length of axis 1 is a.shape[1].
Seeing an axis as a line of values
An aggregation along an axis combines values that sit on the same line in that direction. To find such a line, fix every index except the one belonging to the axis and let that one vary.
For axis 0 of a, fix the column and let the row index vary:
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(a[:, 0]) # [1 4] column 0: row index varies
print(a[:, 1]) # [2 5]
print(a[:, 2]) # [3 6]These are the three lines that run along axis 0. For axis 1, fix the row and let the column index vary:
print(a[0, :]) # [1 2 3] row 0: column index varies
print(a[1, :]) # [4 5 6]These are the two lines that run along axis 1.
Now you can preview the axis argument. a.sum(axis=0) adds up each of the three axis-0 lines and returns [5 7 9]. a.sum(axis=1) adds up each of the two axis-1 lines and returns [ 6 15]. The next chapters cover this in detail. For now, keep one rule in mind: choosing an axis means choosing which index varies inside each group.
One-dimensional arrays
A one-dimensional array has a shape with a single entry, such as (3,). The trailing comma is how Python writes a one-element tuple. Such an array has only axis 0.
import numpy as np
v = np.array([10, 20, 30])
print(v.shape) # (3,)
print(v.ndim) # 1It is not a row and it is not a column. It is a flat sequence. The shapes (3,), (1, 3), and (3, 1) all hold three numbers but are different arrays:
import numpy as np
v = np.array([10, 20, 30])
row = v.reshape(1, 3)
col = v.reshape(3, 1)
print(v.shape) # (3,)
print(row.shape) # (1, 3)
print(col.shape) # (3, 1)
print(row) # [[10 20 30]]
print(col)
# [[10]
# [20]
# [30]]This difference becomes important when you combine arrays by broadcasting. A reduction that removes an axis can turn a (2, 3) array into a (2,) array, which is neither a row nor a column. Chapter-by-chapter, you will learn to restore the missing axis.
Three dimensions and beyond
The same rule extends to any number of dimensions. A three-dimensional array has axes 0, 1, and 2, and indexes like b[i, j, k].
import numpy as np
b = np.arange(24).reshape(2, 3, 4)
print(b.shape) # (2, 3, 4)
print(b.ndim) # 3
print(b.size) # 24You can read (2, 3, 4) as "2 blocks, each with 3 rows and 4 columns". That reading is a convenience, not a NumPy concept. What NumPy guarantees is the index order: b[i, j, k] uses i along axis 0, j along axis 1, and k along axis 2.
Fixing one index with an integer removes that axis from the shape. Leaving it as : keeps it:
print(b[0].shape) # (3, 4) axis 0 fixed
print(b[:, 0, :].shape) # (2, 4) axis 1 fixed
print(b[:, :, 0].shape) # (2, 3) axis 2 fixed
print(b[:, 0:1, :].shape) # (2, 1, 4) slice keeps the axis with length 1The last line shows a distinction you will need again. An integer index drops an axis. A slice such as 0:1 keeps it with length 1. The keepdims option in a later chapter exists for the same reason.
Negative axes
Like list indexes, axis numbers can be negative. axis=-1 is the last axis and axis=-2 is the second to last. Negative axes are convenient when you write code that must work for arrays of different dimension counts, because the last axis is always -1.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
b = np.arange(24).reshape(2, 3, 4)
print(a.shape[-1]) # 3
print(b.shape[-1]) # 4For the two-dimensional a, axis=-1 and axis=1 are the same axis. For the three-dimensional b, axis=-1 is axis 2.
Valid and invalid axes
An axis must satisfy -ndim <= axis < ndim. Anything outside that range raises an error:
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
try:
a.sum(axis=2)
except Exception as e:
print(type(e).__name__) # AxisError
print(e) # axis 2 is out of bounds for array of dimension 2A common cause is a shape that is not what you assumed. A one-dimensional array has no axis 1, so v.sum(axis=1) fails for v of shape (3,). When you get an axis error, print a.shape first.
A habit that prevents mistakes
Before any operation that takes an axis, write down the shape and name the axis you want:
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
n_rows, n_cols = a.shape
print(n_rows, n_cols) # 2 3
# axis 0 has length n_rows, axis 1 has length n_cols
assert a.shape[0] == n_rows
assert a.shape[1] == n_colsTuple unpacking of a.shape gives each axis a name, which makes later code easier to read and check. The idea scales: the length of the axis you reduce is the number of values combined into each result, and the other axes stay.
Summary of the model
shapeis a tuple,ndimis its length, andsizeis the product of its entries.- An axis is a position in the shape tuple, counted from 0. Negative values count from the end.
- For
a[i, j], axis 0 isiand axis 1 isj. - A line along an axis is what you get by fixing all other indexes and letting that one vary.
- Integer indexing drops an axis, and slicing keeps it.
- A one-dimensional array of shape
(n,)has only axis 0, and it differs from(1, n)and(n, 1).
Exercise
An array x has shape (4, 5, 6). (a) What are x.ndim and x.size? (b) What is the shape of x[:, 2, :]? (c) What is the shape of x[:, 2:3, :]? (d) Is axis=3 valid for x? Is axis=-3?
Show answer
(a) ndim is 3 and size is 4 × 5 × 6 = 120. (b) (4, 6), because the integer index 2 removes axis 1. (c) (4, 1, 6), because the slice 2:3 keeps axis 1 with length 1. (d) axis=3 is invalid, since valid values run from -3 to 2 for a three-dimensional array, so NumPy raises an AxisError. axis=-3 is valid and means axis 0.
Exercise
Using a = np.array([[1, 2, 3], [4, 5, 6]]), write the two expressions that select the lines running along axis 0 for column 2, and along axis 1 for row 1. What values does each give?
Show answer
a[:, 2] gives [3 6], and the row index varies along axis 0. a[1, :] gives [4 5 6], and the column index varies along axis 1.