Sub topic 3
Indexing and Slicing
This chapter assumes you know basic Python (lists, loops, functions), can import NumPy, and have a rough idea of vectors and matrices. It also assumes you can read an array's shape, ndim and dtype, which the previous chapters covered. Here you will learn how to select data from an array with integers and slices, and how the result's shape follows from what you write.
Indexing with one index per axis
A NumPy array with ndim axes takes up to ndim indices, separated by commas inside one pair of brackets. Each index applies to one axis, starting with axis 0.
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]a[1, 2] picks row 1 and column 2, which is the value 6. The colon in a[:, 1] means "every position on this axis", so the expression takes column 1 from every row.
Python lists of lists use a different form, a[1][2]. That also works on arrays, but it is slower and misleading. a[1] first builds a whole new row array, and then [2] indexes into that. Use a[1, 2] instead. It is a single operation, and it is the only form that works for slices on several axes at once.
Indexing that removes an axis
An integer index removes its axis from the result. A slice keeps its axis, even if the slice picks only one position.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[1].shape) # (4,) integer: axis 0 is gone
print(a[1:2].shape) # (1, 4) slice: axis 0 is kept, with length 1
print(a[:, 1].shape) # (3,)
print(a[:, 1:2].shape) # (3, 1)This distinction matters a great deal later, when you line up shapes for broadcasting. To pull out a column as a column (shape (3, 1)) rather than a flat vector (shape (3,)), use the slice 1:2 instead of the integer 1.
Negative indices and missing indices
Negative indices count from the end, as in lists. a[-1, -1] is the last element of the last row. If you give fewer indices than ndim, the remaining axes are taken in full, so a[1] is the same as a[1, :].
The ellipsis ... stands for "as many full slices as needed". It is useful when you do not know the number of axes.
import numpy as np
b = np.arange(24).reshape(2, 3, 4)
print(b[..., 0].shape) # (2, 3) same as b[:, :, 0]
print(b[0, ...].shape) # (3, 4) same as b[0, :, :]You can use only one ... in an index.
Slices: start, stop, step
A slice has the form start:stop:step. It follows the same rules as list slicing:
startis included andstopis excluded.- Any of the three parts can be left out. The defaults are the start of the axis, the end of the axis, and a step of 1.
- A negative step walks backwards.
- Out-of-range slice bounds are clipped instead of raising an error.
import numpy as np
v = np.arange(10)
print(v[2:7]) # [2 3 4 5 6]
print(v[::3]) # [0 3 6 9]
print(v[::-1]) # [9 8 7 6 5 4 3 2 1 0]
print(v[7:100]) # [7 8 9]Slices on a 2-D array combine freely.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[:2, 1:3])
# [[1 2]
# [5 6]]
print(a[::2, ::2])
# [[ 0 2]
# [ 8 10]]The first line selects the first two rows and columns 1 and 2, which gives a 2×2 block. The second takes every second row and every second column.
The next diagram shows how one index expression is split across axes.
Out-of-range integer indices still fail
Slices are forgiving, but a single integer is not. a[5, 0] on a (3, 4) array raises IndexError. This difference catches people who test code on small inputs. A slice such as a[5:6] quietly returns an empty array with shape (0, 4), and the empty result can then flow through later steps without any error.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[5:6].shape) # (0, 4)
try:
a[5, 0]
except IndexError as err:
print('error:', err)Assigning through an index
An index expression can be on the left of an assignment, which changes the original array in place. You can assign one number, which is broadcast over the selected region, or an array of matching shape.
import numpy as np
a = np.zeros((3, 4), dtype=int)
a[0, :] = 7 # one value fills the whole row
a[1:, 1:3] = [[1, 2], [3, 4]]
print(a)
# [[7 7 7 7]
# [0 1 2 0]
# [0 3 4 0]]Assignment keeps the array's dtype. Assigning 2.9 into an integer array stores 2, because NumPy truncates to fit the dtype without warning. If you expect fractions, create the array with a float dtype.
Slices are views
A basic slice does not copy data. It returns a new array object that looks at the same memory as the original. Changing the slice changes the original. The next chapter covers this in detail, but you need the basic fact now, because it affects how you write slicing code.
import numpy as np
a = np.arange(12).reshape(3, 4)
col = a[:, 1] # basic slice: a view
col[0] = 99
print(a[0, 1]) # 99, the original changedViews are why slicing is fast even on huge arrays: only a small header with shape and strides is created. They are also why you must call .copy() when you want to edit a piece without touching the source.
import numpy as np
a = np.arange(12).reshape(3, 4)
safe = a[:, 1].copy()
safe[0] = 99
print(a[0, 1]) # 1, unchangedYou can test whether an array shares memory with another with np.shares_memory(a, col), which returns True for the view above.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Using `a[i][j]` in a loop | Works, but builds a temporary row each time and is slower | Use `a[i, j]` |
| Too many indices, such as `a[0, 1, 2]` on a 2-D array | `IndexError: too many indices for array` | Check `a.ndim` first |
| Using an integer where you need a column vector | Result has shape `(3,)` instead of `(3, 1)` | Use `a[:, 1:2]` |
| Editing a slice and expecting the source to stay the same | The source changes too | Call `.copy()` |
| Assigning floats into an integer array | Values are truncated silently | Create the array with `dtype=float` |
Reading shapes from index expressions
You can predict the result shape without running code. Walk through the axes. An integer drops the axis. A slice keeps the axis and sets its length to the number of positions selected. Axes not mentioned keep their full length.
For b = np.arange(24).reshape(2, 3, 4):
b[1]drops axis 0, so the shape is(3, 4).b[:, 2]drops axis 1, so the shape is(2, 4).b[:, ::2, 1:]keeps all axes: 2 positions on axis 0, 2 on axis 1 (positions 0 and 2), and 3 on axis 2, so the shape is(2, 2, 3).
When you have a doubt, print .shape of the intermediate result. This habit pays off in the broadcasting chapters, where most bugs are shape bugs.
Exercise
Given a = np.arange(20).reshape(4, 5), write an expression that returns the last two rows and every second column, and state its shape. Then write an expression that returns column 3 as a 2-D array of shape (4, 1).
Show answer
a[-2:, ::2] selects rows 2 and 3 and columns 0, 2 and 4, so the shape is (2, 3). For the column, use a slice of length one so the axis is kept: a[:, 3:4], which has shape (4, 1). Using a[:, 3] would give shape (4,).
Exercise
What does the following code print, and why? import numpy as np a = np.arange(6) b = a[1:4] b[:] = 0 print(a)
Show answer
It prints [0 0 0 0 4 5]. The slice a[1:4] is a view, so assigning zero to b[:] writes into the memory shared with a. Positions 1, 2 and 3 of a become 0.