Sub topic 1
Array shape and axes: what an index addresses
Prerequisites
This chapter assumes you already know the following:
- Basic Python syntax, including lists and list slicing.
- How to create NumPy arrays with
np.array,np.arange, andreshape. - What an array's
shapeanddtypeare.
You do not need any prior knowledge of NumPy indexing. This chapter sets up the vocabulary that the rest of the tutorial uses: shape, dimension, axis, and what a single index value points at.
Why shape comes before indexing
Every indexing operation in NumPy is a statement about a specific axis of a specific array. If you misjudge the shape, you will select the wrong data, and NumPy will often not warn you. It will return something that looks plausible.
The working model has three parts:
- An array has a shape, a tuple of integers that gives the length of each axis.
- Each position in the index tuple addresses one axis, in order.
- The result's shape is determined by the shape of the original and by what kind of index you place on each axis.
This chapter covers parts 1 and 2. Later chapters cover part 3 in detail for integers, slices, arrays, and masks.
Shape, ndim, size, and axes
The shape attribute is a tuple. Its length is the number of dimensions, and each entry is the number of elements along one axis.
import numpy as np
a = np.arange(24).reshape(2, 3, 4)
print(a.shape) # (2, 3, 4)
print(a.ndim) # 3
print(a.size) # 24
print(len(a)) # 2, the length of axis 0 onlyThe attributes mean the following:
| Attribute | Meaning | Value for `a` |
|---|---|---|
| `a.shape` | Length of each axis | `(2, 3, 4)` |
| `a.ndim` | Number of axes, equal to `len(a.shape)` | `3` |
| `a.size` | Total number of elements, the product of the shape | `24` |
| `len(a)` | Length of axis 0 only | `2` |
The term dimension is used in two senses. In "a 3-dimensional array", it means the number of axes (ndim). In "the second dimension has length 3", it means a single axis. This tutorial uses axis for a single direction and ndim for the count, to avoid confusion.
Axes are numbered from 0. For a 2-D array, axis 0 runs down the rows and axis 1 runs across the columns. For a 3-D array of shape (2, 3, 4), you can think of 2 blocks, each with 3 rows and 4 columns. Axis 0 selects the block, axis 1 selects the row inside the block, and axis 2 selects the column inside the row.
The diagram expands only the first block and its first row. The second block has the same structure.
One index entry per axis
An index expression such as a[i, j, k] is a tuple (i, j, k). NumPy matches the entries to axes from left to right. The first entry addresses axis 0, the second addresses axis 1, and so on.
import numpy as np
a = np.arange(24).reshape(2, 3, 4)
print(a[1, 2, 3]) # 23, last block, last row, last column
print(a[1, 0, 0]) # 12, first element of the second blockThe array holds the values 0 to 23 in row-major order, which NumPy calls C order. The last axis changes fastest as you step through memory. Element a[1, 0, 0] is 12 because the first block holds 3 × 4 = 12 elements.
You can check this with the formula for a flat position in C order:
import numpy as np
a = np.arange(24).reshape(2, 3, 4)
i, j, k = 1, 2, 3
flat = i * (3 * 4) + j * 4 + k
print(flat) # 23
print(a.ravel()[flat]) # 23
print(a[i, j, k]) # 23You rarely compute this yourself. The point is that an index always refers to a coordinate in the shape, not to a position in a flat sequence.
Fewer indices than axes
If you supply fewer index entries than the array has axes, the missing entries at the end are treated as "take everything" on those axes. The result is a sub-array.
import numpy as np
a = np.arange(24).reshape(2, 3, 4)
print(a[1].shape) # (3, 4), same as a[1, :, :]
print(a[1, 2].shape) # (4,), same as a[1, 2, :]
print(a[1, 2]) # [20 21 22 23]An integer index removes its axis from the result. A full integer index with one entry per axis removes every axis and gives a scalar. A partial integer index gives an array with ndim reduced by the number of integers you supplied.
| Expression | Result shape | Result `ndim` |
|---|---|---|
| `a` | `(2, 3, 4)` | 3 |
| `a[1]` | `(3, 4)` | 2 |
| `a[1, 2]` | `(4,)` | 1 |
| `a[1, 2, 3]` | scalar | 0 |
A full integer index gives a NumPy scalar such as np.int64, not a 0-D array. This difference rarely matters, but it explains why a[1, 2, 3].shape returns ().
Too many indices
Supplying more entries than ndim raises an error. The message names the problem directly.
import numpy as np
a = np.arange(12).reshape(3, 4)
try:
a[1, 2, 3]
except IndexError as e:
print(e) # too many indices for array: array is 2-dimensional, but 3 were indexedA related error occurs when an integer is outside the length of its axis. Each axis has its own valid range, from -n to n - 1 for an axis of length n.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[2, 3]) # 11, the last valid element
print(a[-3, -4]) # 0, the first element, written with negative indices
try:
a[3, 0]
except IndexError as e:
print(e) # index 3 is out of bounds for axis 0 with size 3Note that the message names the axis and its size. When you get this error on a multi-axis array, check which axis failed. A common mistake is to swap row and column indices and trigger the error on an axis that is shorter than the one you intended.
Shape is not the same as nesting
A Python list of lists can have rows of different lengths. A NumPy array cannot. Its shape is a single tuple, so every row along an axis has the same length. This regularity is what lets one index tuple address any element with arithmetic.
import numpy as np
nested = [[1, 2, 3], [4, 5, 6]]
arr = np.array(nested)
print(arr.shape) # (2, 3)
print(nested[1][2]) # 6, two separate lookups
print(arr[1, 2]) # 6, one lookup with a tupleThe two forms arr[1][2] and arr[1, 2] return the same value, but they are not equivalent. arr[1][2] first builds the intermediate row arr[1], then indexes it. arr[1, 2] addresses the element directly. For plain integers the cost is small. For slices, arrays, and masks, the two forms can give different results, so use the comma form as a habit.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[0:2][1]) # [4 5 6 7], slice first, then take row 1 of the result
print(a[0:2, 1]) # [1 5], rows 0 and 1, column 1The first expression slices rows and then picks one row. The second applies the row slice and the column index in the same step. The outputs differ because the second index in the chained form applies to axis 0 of the intermediate result, not to axis 1 of the original.
Shapes with length 1 and length 0
Two special lengths cause frequent confusion.
An axis of length 1 is a real axis. The shapes (3,), (3, 1), and (1, 3) hold the same three values but are different arrays, and they index differently.
import numpy as np
v = np.array([10, 20, 30])
col = v.reshape(3, 1)
row = v.reshape(1, 3)
print(v.shape, col.shape, row.shape) # (3,) (3, 1) (1, 3)
print(v[2]) # 30
print(col[2, 0]) # 30
print(row[0, 2]) # 30Indexing col[2] gives [30], an array of shape (1,), because only axis 0 was addressed. A later chapter on np.newaxis shows how to add and remove such axes on purpose.
An axis of length 0 is also valid. The array is empty, and no integer index is valid on that axis.
import numpy as np
empty = np.zeros((0, 3))
print(empty.shape) # (0, 3)
print(empty.size) # 0
try:
empty[0, 0]
except IndexError as e:
print(e) # index 0 is out of bounds for axis 0 with size 0Empty arrays appear in practice when a filter matches nothing. Code that assumes at least one row will fail on them, so check size or shape[0] when the input is not under your control.
Inspecting shape while you work
Most indexing bugs show up as a wrong shape, so printing shapes is the fastest check. A small helper makes this routine.
import numpy as np
def describe(name, x):
x = np.asarray(x)
print(f"{name}: shape={x.shape}, ndim={x.ndim}, dtype={x.dtype}")
a = np.arange(24).reshape(2, 3, 4)
describe("a", a)
describe("a[0]", a[0])
describe("a[0, 1]", a[0, 1])
describe("a[0, 1, 2]", a[0, 1, 2])The output is:
a: shape=(2, 3, 4), ndim=3, dtype=int64
a[0]: shape=(3, 4), ndim=2, dtype=int64
a[0, 1]: shape=(4,), ndim=1, dtype=int64
a[0, 1, 2]: shape=(), ndim=0, dtype=int64The dtype may print as int32 on some platforms, such as Windows with older NumPy versions. The shapes do not depend on the platform.
Before you write a complex index, state the expected result shape. After you run it, compare. A mismatch tells you which axis you misread.
Common errors at this stage
- Reading
shapeas (columns, rows). NumPy lists axis 0 first. For a 2-D array,shapeis(rows, columns). - Using
len(a)as the element count. It returns only the length of axis 0. Usea.sizefor the total. - Swapping axes in an index.
a[col, row]on a(rows, columns)array addresses the wrong element or raises anIndexError. - Treating
(n,)as a column or a row. A 1-D array has no orientation. It is neither(n, 1)nor(1, n). - Chaining indices with
a[i][j]when slices are involved. Usea[i, j], so each entry maps to its own axis.
Exercise
An array is created with a = np.arange(60).reshape(3, 4, 5). Give the shape of a[2], the shape of a[2, 1], and the value of a[2, 1, 4]. Then explain why a[3] raises an error.
Show answer
a[2] has shape (4, 5), because the integer removes axis 0. a[2, 1] has shape (5,). The value of a[2, 1, 4] is 2 20 + 1 5 + 4 = 49. a[3] raises an IndexError because axis 0 has length 3, so the valid indices are -3 to 2.
Exercise
You have v = np.array([1, 2, 3, 4]). What are the shapes of v.reshape(4, 1) and v.reshape(1, 4), and what does v.reshape(4, 1)[2] return?
Show answer
The shapes are (4, 1) and (1, 4). v.reshape(4, 1)[2] addresses only axis 0, so it returns array([3]), an array of shape (1,), not the scalar 3.