Sub topic 11
Mixing slices, integers, arrays, and masks
This chapter assumes you know integer indexing, slicing, views versus copies, boolean masks, and fancy indexing from the earlier chapters. Real code often combines these in one subscript, such as a[mask, 1:3]. Predicting the result takes a few rules.
One index per axis
A subscript separated by commas gives one index to each axis, left to right. Axes you leave out are taken whole. Each kind of index treats its axis differently:
| Index type | Effect on its axis | Memory |
|---|---|---|
| Integer | Axis is removed | View |
| Slice | Axis is kept, possibly shorter | View |
| Integer array or boolean mask | Axis is replaced by the index shape | Copy |
If any index is an array or mask, NumPy uses advanced indexing and returns a copy.
Slices with integers
An integer inside a slice expression removes that axis and keeps the view behavior.
import numpy as np
a = np.arange(24).reshape(2, 3, 4)
print(a[0, :, 1]) # [1 5 9], shape (3,)
print(a[:, 1:, 0].shape) # (2, 2)Slices with arrays and masks
You can apply an array or mask to one axis and a slice to another. The slice part is applied to each selected item.
import numpy as np
a = np.arange(24).reshape(2, 3, 4)
print(a[:, [0, 2], 1:3])
# [[[ 1 2]
# [ 9 10]]
#
# [[13 14]
# [21 22]]]
b = np.arange(12).reshape(3, 4)
print(b[b[:, 0] > 0, 1:3])
# [[ 5 6]
# [ 9 10]]The second line is a common pattern: choose rows by a condition on one column, then keep only some columns. The mask b[:, 0] > 0 has length 3, so it applies to axis 0.
Assignment through mixed indices
Assignment works with mixed indices, and it writes into the original array. This is because the assignment form b[...] = value runs on b itself, not on a temporary copy.
import numpy as np
b = np.arange(12).reshape(3, 4)
b[[0, 2], 1:3] = 0
print(b)
# [[ 0 0 0 3]
# [ 4 5 6 7]
# [ 8 0 0 11]]Pitfall: separated advanced indices
If array indices (or an integer next to an array) are separated by a slice, NumPy puts the broadcast dimension first in the result. The slice dimensions follow.
import numpy as np
a = np.arange(24).reshape(2, 3, 4)
print(a[[0, 1], :, [0, 1]].shape) # (2, 3), not (3, 2)
print(a[[0, 1], :, [0, 1]])
# [[ 0 4 8]
# [13 17 21]]
print(a[0, :, [0, 1]].shape) # (2, 3): the integer counts as an array here
print(a[0][:, [0, 1]].shape) # (3, 2): two steps, two separate rulesIf you want the slice axis in its natural position, split the subscript into two steps, as in a[0][:, [0, 1]]. This is safe for reading. It is not safe for writing, as the next section shows.
Pitfall: chained indexing and assignment
Each subscript in a chain is evaluated separately. If the first one is advanced, it makes a copy, and the second one then writes into that copy.
import numpy as np
b = np.arange(12).reshape(3, 4)
rows = b[:, 0] > 0
b[rows][:, 1] = 0 # writes into a temporary copy
print(b[1]) # [4 5 6 7], unchanged
b[rows, 1] = 0 # one subscript, writes into b
print(b[1]) # [4 0 6 7]Debugging checklist
- Print
.shapeof each index and of the result before building a longer expression. - Count the axes: every integer removes one, and a mask of ndim
kconsumeskaxes. - Check whether array indices are adjacent. If a slice sits between them, expect the broadcast dimension first.
- For writes, use one subscript, then check that the original array changed.
Exercise
Given a = np.arange(24).reshape(2, 3, 4), what is the shape of a[:, [0, 2], 1:3], and what is the shape of a[[0, 1], :, [0, 1]]? Explain why the second one differs from what you might expect.
Show answer
The first is (2, 2, 2): the slice on axis 0 keeps 2 items, the array picks 2 items on axis 1, and the slice 1:3 keeps 2 on axis 2. The second is (2, 3). The two array indices are separated by a slice, so NumPy broadcasts them into one dimension of length 2 and puts it first, followed by the sliced axis of length 3. The result is not (3, 2).