Sub topic 3
Indexing and slicing
This chapter assumes you know basic Python lists and slicing, and that you have met an array's shape and ndim. Here you will learn to select single elements and sub-arrays from a NumPy array. You will also see how the result's shape follows from the index you write.
One index per axis
A NumPy array takes one index for each axis, separated by commas inside a single pair of brackets. This differs from nested lists, where you chain brackets like a[1][2]. The two forms give the same value for a 2D array, but a[1, 2] is faster and is the only form that works with slices on more than one axis.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a.shape) # (3, 4)
print(a.ndim) # 2
print(a[1, 2]) # 6
print(a[:, 1]) # [1 5 9]The array a looks like this:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]Negative indices count from the end, so a[-1, -1] is 11.
Slices
A slice has the form start:stop:step. The stop position is excluded, and any part can be left out. A lone : means "everything along this axis".
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[0]) # [0 1 2 3]
print(a[1:, :2]) # [[4 5]
# [8 9]]
print(a[::2]) # rows 0 and 2
print(a[0, ::-1]) # [3 2 1 0]
print(a[..., 0]) # [0 4 8]The last line uses ... (Ellipsis). It stands for "as many : as needed", so a[..., 0] selects the first entry along the last axis whatever ndim is. If you give fewer indices than there are axes, NumPy fills in the missing ones with :. That is why a[0] returns a whole row.
Integers remove axes, slices keep them
This rule matters most for later chapters. An integer index removes its axis from the result. A slice keeps the axis, even when it selects only one position.
| Expression | Result shape | Why |
|---|---|---|
| `a[1]` | `(4,)` | The integer removes axis 0. |
| `a[1:2]` | `(1, 4)` | The slice keeps axis 0 with length 1. |
| `a[:, 1]` | `(3,)` | The integer removes axis 1. |
| `a[:, 1:2]` | `(3, 1)` | The slice keeps axis 1 with length 1. |
A column of shape (3,) and a column of shape (3, 1) behave differently once you start combining arrays. When you need to keep the column as a 2D object, use a slice such as 1:2 instead of the integer 1.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[:, 1].shape) # (3,)
print(a[:, 1:2].shape) # (3, 1)Slices can write, too
You can assign to an indexed region. NumPy broadcasts the right-hand side to the selected shape.
import numpy as np
a = np.arange(12).reshape(3, 4)
a[0, :] = 0 # a scalar fills the whole row
a[1:, 1:3] = [10, 20] # a length-2 row fills each selected row
print(a)
# [[ 0 0 0 0]
# [ 4 10 20 7]
# [ 8 10 20 11]]Common errors
- Out-of-range integer indices raise
IndexError. Out-of-range slice bounds do not. They are clipped, soa[:, 2:100]quietly returns columns 2 and 3. - Giving too many indices, such as
a[0, 1, 2]on a 2D array, raisesIndexError. - Slices of arrays are not copies. Changing a slice changes the original array. The next chapter covers this in detail.
Exercise
For a = np.arange(12).reshape(3, 4), what are the shape and contents of a[1:, ::2]?
Show answer
The shape is (2, 2). The slice 1: keeps rows 1 and 2, and ::2 keeps columns 0 and 2. The result is [[4 6] [8 10]].