Sub topic 5
Indexing and slicing
This chapter assumes you know Python list indexing and slicing, and that you can create arrays and read their shape and ndim (covered in earlier chapters).
Indexing with one index per axis
A NumPy array takes one index for each axis, separated by commas. For a 2-D array, the first index picks the row and the second picks the column.
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[1, 2]) # 6
print(a[-1, -1]) # 11, negative indexes count from the end
print(a[1][2]) # 6, same value, but builds a temporary row firstPrefer a[1, 2] over a[1][2]. The chained form creates an intermediate array and is slower. It also behaves differently once you start assigning through slices.
If you give fewer indexes than the array has axes, the missing ones default to a full slice. So a[0] is the whole first row.
Slicing with start:stop:step
A slice uses the form start:stop:step. The stop value is excluded, as in Python lists. You can slice each axis independently.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[0]) # [0 1 2 3], the first row
print(a[:, 1]) # [1 5 9], every row, column 1
print(a[1:, ::2]) # [[ 4 6]
# [ 8 10]], rows 1 onward, every second column
print(a[..., 0]) # [0 4 8], ... stands for "all remaining axes"The ellipsis ... is useful when you don't know how many axes the array has. It expands to as many full slices as needed.
Integers drop an axis, slices keep it
This is the most common source of shape surprises. An integer index removes that axis from the result. A slice keeps it, even when it selects only one element.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[:, 1].shape) # (3,), the column axis was dropped
print(a[:, 1:2].shape) # (3, 1), the column axis was keptUse 1:2 instead of 1 when you need the result to stay two-dimensional. This matters later when you combine arrays with broadcasting.
Assigning through indexes and slices
You can assign to any selection. NumPy broadcasts the right-hand side to fit.
import numpy as np
a = np.arange(12).reshape(3, 4)
a[0, :] = 0 # a scalar fills the whole row
a[:, 1] = [10, 20, 30] # one value per row
print(a)
# [[ 0 10 0 0]
# [ 4 20 6 7]
# [ 8 30 10 11]]A basic slice refers to the original data rather than copying it, so assigning through it changes a. The next chapter covers this behavior in detail.
Out-of-range behavior
Single indexes are strict, but slices are forgiving.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[:, 10:].shape) # (3, 0), an empty slice is not an error
try:
a[5, 0]
except IndexError as e:
print(e) # index 5 is out of bounds for axis 0 with size 3An out-of-range integer raises IndexError. An out-of-range slice is clipped, and it can silently return an empty array. If a result is unexpectedly empty, check your slice bounds.
Common errors
- Too many indexes.
a[0, 1, 2]on a 2-D array raisesIndexError: too many indices for array. Checka.ndimfirst. - Wrong shape on assignment.
a[:, 1] = [1, 2]fails because 2 values cannot broadcast into 3 rows. - Forgetting the dropped axis. Code that expects a column of shape
(3, 1)receives(3,)aftera[:, 1].
Exercise
Given a = np.arange(12).reshape(3, 4), what are the values and shape of a[1:, ::2]?
Show answer
Rows 1 and 2 are kept, and columns 0 and 2 are kept. The result is [[4, 6], [8, 10]] with shape (2, 2).