Sub topic 1
Array shape and axes: what an index addresses
Prerequisites
This chapter assumes you can do the following:
- Write basic Python, including lists and list slicing.
- Create arrays with
np.array,np.arange, andreshape. - Say what an array's
shapeanddtypeare.
Every later chapter builds on one idea: an index is an address, and the array's shape decides which addresses exist. This chapter fixes that idea first.
Shape, dimensions, and axes
An ndarray is a block of values of one dtype, arranged on a grid. Three attributes describe the grid:
shapeis a tuple with the length of each axis.ndimis the number of axes, which equalslen(shape).sizeis the total number of elements, which is the product of the shape.
An axis is one direction along the grid. Axes are numbered from 0. In a 2-D array, axis 0 runs down the rows and axis 1 runs across the columns.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
print(a.shape) # (3, 4)
print(a.ndim) # 2
print(a.size) # 12Here shape is (3, 4): axis 0 has length 3 (three rows) and axis 1 has length 4 (four columns).
One index per axis
An index addresses a position by giving one entry per axis, in axis order. For a above, a[1, 2] means "position 1 on axis 0, position 2 on axis 1". That is the value 6.
Valid positions on an axis run from 0 to length - 1. Negative positions count from the end, so -1 is the last. An index outside that range raises IndexError.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[2, 3]) # 11, the last row and last column
print(a[-1, -1]) # 11, same element using negative positions
try:
a[3, 0] # axis 0 has length 3, so valid positions are 0, 1, 2
except IndexError as err:
print(err) # index 3 is out of bounds for axis 0 with size 3The error message names the axis and its size. When you debug an index error, compare that axis length with the number you used.
Fewer indices than axes
If you give fewer entries than the array has axes, NumPy fills the remaining axes with "everything". The result has fewer dimensions.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[1]) # [4 5 6 7]
print(a[1].shape) # (4,)
print(a[1, :]) # [4 5 6 7], the same thing written outa[1] is a 1-D row with shape (4,), not a 2-D array with shape (1, 4). Each integer index removes one axis from the result. This rule explains many shape surprises in later chapters.
Three dimensions
The same rule extends to more axes. Read the shape left to right as "how many blocks, how many rows, how many columns".
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[1].shape) # (3, 4), one integer removed axis 0
print(b[1, 2].shape) # (4,), two integers removed two axesThe shape (2, 3, 4) means 2 blocks, each holding 3 rows of 4 values. Always check shape before writing an index. Most indexing bugs come from guessing it wrong.
Summary of the rules
| Idea | Rule | Example on shape (3, 4) |
|---|---|---|
| One entry per axis | Entries are matched to axes in order | `a[1, 2]` is a single value |
| Valid range | `-length` to `length - 1` on each axis | `a[3, 0]` raises `IndexError` |
| Fewer entries | Remaining axes are kept whole | `a[1]` has shape `(4,)` |
| Integer index | Removes its axis from the result | `a[1, 2]` has no axes left |
Exercise
An array c has shape (4, 5, 6). What are the shapes of c[2] and c[2, 3], and what happens with c[4, 0, 0]?
Show answer
c[2] has shape (5, 6) and c[2, 3] has shape (6,), because each integer removes one axis. c[4, 0, 0] raises IndexError, because axis 0 has length 4 and the valid positions are 0 to 3 (or -4 to -1).
Exercise
What does np.arange(20).reshape(4, 5)[-1, 1] return, and why?
Show answer
It returns 16. The last row (position -1) is [15 16 17 18 19], and position 1 in that row is 16.