Sub topic 1
Array shape and what an axis is
Prerequisites
This chapter assumes you can write basic Python, create arrays with np.array and np.arange, and read an array's shape. Later chapters build on the idea of an axis introduced here.
Shape lists the length of each dimension
The shape of an array is a tuple with one length per dimension. A two-dimensional array has a shape of the form (rows, columns).
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) # 6ndim is the number of dimensions, which equals len(a.shape). size is the total number of elements, which is the product of the shape entries.
An axis is a position in the shape
An axis is one dimension of the array, identified by its position in the shape tuple. Axis numbering starts at 0.
| Axis | Position in `(2, 3)` | Length | Usual name in 2-D |
|---|---|---|---|
| 0 | first | 2 | rows |
| 1 | second | 3 | columns |
The axis number matches the position of the index you write in a[i, j]. Axis 0 is the i index and axis 1 is the j index.
Seeing an axis through indexing
Fixing the index on one axis and slicing the other shows what each axis does.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(a[0, :]) # [1 2 3] axis 0 fixed at 0, axis 1 varies
print(a[:, 0]) # [1 4] axis 1 fixed at 0, axis 0 varies
print(a.shape[0]) # 2
print(a.shape[-1]) # 3Negative numbers count from the end, so -1 always means the last axis. This works for shape[-1] and also for the axis argument of NumPy functions.
Axes beyond two dimensions
The words "row" and "column" stop being useful at three dimensions, but the position rule still holds.
import numpy as np
b = np.arange(24).reshape(2, 3, 4)
print(b.shape) # (2, 3, 4)
print(b[1, 2, 3]) # 23
print(b.shape[2]) # 4Here axis 0 has length 2, axis 1 has length 3 and axis 2 has length 4. In b[1, 2, 3], the three indices belong to axes 0, 1 and 2 in that order.
Why this matters for aggregation
An aggregation such as sum or max reduces an array to fewer values. The axis argument names the axis that gets collapsed. That axis disappears from the shape, and the other axes remain.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(a.sum(axis=0)) # [5 7 9]
print(a.sum(axis=1)) # [ 6 15]Starting from shape (2, 3), axis=0 removes the length-2 axis and leaves shape (3,). Using axis=1 removes the length-3 axis and leaves shape (2,).
The next chapters apply this rule to sums, means and other reductions. Before moving on, make sure you can read any shape tuple and say which axis is which.
Exercise
An array x has shape (4, 5, 6). What is the shape of x.sum(axis=1), and what does x.shape[-1] return?
Show answer
The result has shape (4, 6), because axis=1 is the length-5 axis and it is removed. x.shape[-1] returns 6, the length of the last axis.