Sub topic 11
Mixing slices, integers, arrays, and masks
Earlier chapters covered each indexing tool alone: integers, slices, integer arrays, and boolean masks. Real code combines them in one expression, such as a[mask, 1:3] or b[0, :, [0, 1]]. This chapter explains how NumPy combines them and how to predict the result shape. It also covers when you get a view or a copy and which combinations fail.
It assumes you know array shape and axes, basic slices, views versus copies, boolean masks, and fancy indexing with integer arrays.
The rule for each index type
Each position in the index tuple addresses one axis, from left to right. What each kind of index does to its axis:
| Index at an axis | Effect on that axis | Part of the result |
|---|---|---|
| Slice (`1:3`, `:`) | Keeps the axis, possibly shorter | Basic indexing, view |
| Integer (`2`) | Removes the axis | Basic indexing when used alone or with slices |
| Integer array or list | Replaces the axis with the array's shape | Advanced indexing, copy |
| Boolean array | Same as `np.nonzero(mask)`, one integer array per mask dimension | Advanced indexing, copy |
Once any array or mask appears in the tuple, the whole expression is advanced indexing, and the result is a copy. Slices and integers in the same tuple still behave as described, but they are evaluated together with the arrays.
Integers with slices
When you mix integers and slices only, each integer removes an axis and each slice keeps one.
import numpy as np
b = np.arange(24).reshape(2, 3, 4)
print(b[1, :, 2]) # [14 18 22]
print(b[1, :, 2].shape) # (3,)
print(b[:, 1, 1:3]) # [[ 5 6]
# [17 18]]
print(b[:, 1, 1:3].shape) # (2, 2)The result is a view, so writing to it changes b. The b[1, :, 2] case picks plane 1, keeps all rows, and takes column 2. The dimension count of the result equals the number of slices.
Slices with one array
A single integer list or array combined with slices is the easy case. The array's axis is replaced by the array's shape, and the position of that axis stays where it was.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[:, [0, 3]]) # [[ 0 3]
# [ 4 7]
# [ 8 11]]
print(a[[0, 2], 1:3]) # [[ 1 2]
# [ 9 10]]
print(a[1, [0, 3]]) # [4 7]a[:, [0, 3]] has shape (3, 2): three rows kept, two columns chosen. a[[0, 2], 1:3] first picks rows 0 and 2, then columns 1 and 2 of those rows.
Selecting columns with a[:, [0, 3]] is a common pattern because it keeps the rows as they are. It always returns a copy, even though the : part alone would give a view.
Slices with a mask
A boolean mask on one axis combines naturally with slices on the others. The usual use is "pick the rows that satisfy a condition, then keep only some columns."
import numpy as np
scores = np.array([
[72, 88, 95, 60],
[55, 40, 62, 70],
[90, 85, 78, 92],
[30, 45, 50, 41],
])
row_mask = scores.mean(axis=1) > 60
print(row_mask) # [ True False True False]
print(scores[row_mask, 1:3]) # [[88 95]
# [85 78]]
scores[row_mask, -1] += 5 # curve the last column for passing rows
print(scores[:, -1]) # [65 70 97 41]The mask must have the same length as the axis it indexes. Here row_mask has length 4 and sits in the row position. The expression scores[row_mask, -1] += 5 works as an assignment: NumPy reads the selected elements, adds 5, and writes them back into scores. Only rows 0 and 2 change.
Two arrays in one index: pairing and broadcasting
When two or more arrays appear in the index, they are broadcast against each other and consumed together, one element from each at a time. They do not form a grid.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[[0, 2], [1, 3]]) # [ 1 11]
print(a[[[0], [2]], [1, 3]]) # [[ 1 3]
# [ 9 11]]
print(a[np.ix_([0, 2], [1, 3])]) # [[ 1 3]
# [ 9 11]]The first line pairs (0, 1) and (2, 3). The second makes the row index a column of shape (2, 1) and the column index a row of shape (2,). These broadcast to (2, 2), which gives every row and column combination. np.ix_ builds exactly that reshaped pair for you.
Index arrays that cannot broadcast raise an error:
import numpy as np
a = np.arange(12).reshape(3, 4)
try:
a[[0, 1, 2], [0, 1]]
except IndexError as err:
print(err) # shape mismatch: indexing arrays could not be broadcast together ...Masks across several axes
A one-dimensional boolean mask is converted to the integer positions where it is True. If you place two such masks in one index, they are paired like two integer arrays, not combined into a grid.
import numpy as np
a = np.arange(12).reshape(3, 4)
rows = np.array([True, False, True])
cols = np.array([False, True, False, True])
print(a[rows, cols]) # [ 1 11]
print(a[np.ix_(rows, cols)]) # [[ 1 3]
# [ 9 11]]Here rows selects positions 0 and 2, and cols selects 1 and 3. Paired, that gives elements (0, 1) and (2, 3). If the two masks have a different number of True values, the pairing fails with a shape mismatch. Use np.ix_ when you want every selected row combined with every selected column. It accepts boolean sequences as well as integer ones.
Where the result dimensions land
Predicting shapes takes one extra rule. NumPy treats integers as advanced indices whenever an array is also present in the tuple. After broadcasting the advanced indices, it places their combined dimensions in one of two ways:
- If all advanced indices sit next to each other in the tuple, the broadcast dimensions replace them in place.
- If a slice (or
np.newaxis) separates them, the broadcast dimensions go first, ahead of all sliced dimensions.
import numpy as np
b = np.arange(24).reshape(2, 3, 4)
adjacent = b[:, [0, 1], [0, 1]]
print(adjacent.shape) # (2, 2)
print(adjacent) # [[ 0 5]
# [12 17]]
separated = b[0, :, [0, 1]]
print(separated.shape) # (2, 3)
print(separated) # [[0 4 8]
# [1 5 9]]
chained = b[0][:, [0, 1]]
print(chained.shape) # (3, 2)In b[0, :, [0, 1]], the integer 0 and the list [0, 1] are both advanced indices, and the : between them separates them. The broadcast dimension, of length 2, therefore comes first, ahead of the sliced axis of length 3. The chained version b[0][:, [0, 1]] does the integer step first, so the list is the only advanced index and the result stays (3, 2).
Views, copies, and assignment
A mixed index returns a copy as soon as it includes an array or mask. That matters when you write.
import numpy as np
a = np.arange(12).reshape(3, 4)
a[[0, 1], 1:3] = 0 # one indexing call, assignment goes into a
print(a)
# [[ 0 0 0 3]
# [ 4 0 0 7]
# [ 8 9 10 11]]
a[[0, 1]][:, 0] = 99 # two steps: the first makes a copy
print(a[0, 0]) # 0, unchangedA single assignment like a[idx] = value is translated into one __setitem__ call on a, so it writes into the original even when idx contains arrays. A chain such as a[[0, 1]][:, 0] = 99 runs a[[0, 1]] first, which creates a temporary copy, then assigns into that copy. The original is untouched and NumPy does not warn you.
Repeated indices in augmented assignment
With repeated positions, += does not accumulate:
import numpy as np
x = np.zeros(3, dtype=int)
x[[0, 0, 1]] += 1
print(x) # [1 1 0]
y = np.zeros(3, dtype=int)
np.add.at(y, [0, 0, 1], 1)
print(y) # [2 1 0]x[idx] += 1 reads x[idx] once, adds 1 to the copy, and writes it back. Position 0 is written twice with the same value. Use np.add.at when duplicates must accumulate.
Common errors with mixed indexing
| Symptom | Likely cause | Fix |
|---|---|---|
| `IndexError: shape mismatch` | Two index arrays or masks that cannot broadcast | Make lengths match, or use `np.ix_` for a grid |
| `IndexError: boolean index did not match` | Mask length differs from the axis length | Build the mask from the same axis, such as `a[:, 0] > 0` for rows |
| Result has an unexpected axis order | Integer and array separated by a slice | Split into two steps, or use slices for the integer part |
| Assignment has no effect | Chained indexing started with an array or mask | Use a single index tuple |
| Counts do not accumulate | `+=` with repeated indices | Use `np.add.at` |
Choosing a combination
- To pick a block of rows and columns, use
a[r0:r1, c0:c1]. It is a view and costs nothing. - To pick arbitrary rows but all columns, use
a[[2, 0, 1]]ora[row_mask]. - To pick arbitrary rows and columns as a block, use
a[np.ix_(rows, cols)]. You can also usea[rows][:, cols]if you only read, because each step has a single array. - To pick individual elements, use
a[rows, cols]with arrays of the same length. - To change values, put the whole selection in one index and assign to it.
Exercise
For c = np.arange(24).reshape(2, 3, 4), what is the shape of c[1, :, [0, 2]], and what is the shape of c[1][:, [0, 2]]? Explain the difference.
Show answer
c[1, :, [0, 2]] has shape (2, 3). The integer 1 and the list are both advanced indices, and the slice between them separates them, so the broadcast dimension of length 2 comes first, followed by the sliced axis of length 3. c[1][:, [0, 2]] has shape (3, 2). The first step c[1] drops the first axis and gives a (3, 4) array, and the second step has only one advanced index, so the sliced axis stays first.
Exercise
With a = np.arange(12).reshape(3, 4), write one line that sets the last two columns to 0 in every row whose first value is greater than 0. What does a look like afterwards?
Show answer
a[a[:, 0] > 0, -2:] = 0. The mask a[:, 0] > 0 is [False, True, True], and -2: selects the last two columns. Afterwards a is [[0, 1, 2, 3], [4, 5, 0, 0], [8, 9, 0, 0]]. Row 0 is unchanged because its first value is 0.