Sub topic 12
Common pitfalls and how to debug them
This chapter assumes you know the indexing tools from the earlier chapters: integer indices, slices, views and copies, boolean masks, and fancy indexing. It collects the mistakes that come up most often and a routine for finding the cause.
Pitfall 1: Operator precedence in masks
In Python, & binds more tightly than > or ==. Without parentheses, NumPy receives a different expression than the one you meant. The words and and or fail for a related reason. They ask whether a whole array is true, and an array has no single answer.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
try:
data[data > 0 & data % 2 == 0]
except ValueError as e:
print("precedence:", e)
try:
data[(data > 0) and (data % 2 == 0)]
except ValueError as e:
print("and:", e)
print(data[(data > 0) & (data % 2 == 0)]) # [4 2]Both failures raise ValueError: The truth value of an array ... is ambiguous. Wrap every comparison in parentheses and combine them with &, |, and ~.
Pitfall 2: Chained indexing that writes to a copy
A slice returns a view, but a mask or an index list returns a copy. If you index twice and assign on the second step, the write may land on a temporary copy.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
data[data > 0][0] = 99
print(data) # [ 4 -1 7 0 -5 2], unchanged
first = np.flatnonzero(data > 0)[0]
data[first] = 99
print(data) # [99 -1 7 0 -5 2]Here data[data > 0] is a new array, and the assignment changes that array and then discards it. Compute the position first and assign with a single index expression.
Pitfall 3: Shape surprises
An integer index removes an axis. A slice of length one keeps it. Many broadcasting errors later in a program trace back to this difference.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[:, 1].shape) # (3,)
print(a[:, 1:2].shape) # (3, 1)
b = np.zeros((2, 3, 4))
print(b[:, [0, 1], [0, 1]].shape) # (2, 2)
print(b[0, :, [0, 1]].shape) # (2, 3)The last line is a known gotcha. When array indices (an integer counts as one) are separated by a slice, NumPy moves the indexed dimension to the front of the result. The result is (2, 3), not (3, 2). If you need a particular layout, check the shape, or split the work into two steps.
Pitfall 4: Mismatched sizes
A boolean mask must have the same length as the axis it indexes. An integer index must be inside the axis.
import numpy as np
a = np.arange(12).reshape(3, 4)
try:
a[np.array([True, False])]
except IndexError as e:
print(e) # boolean index did not match ... size of axis is 3 ...
try:
a[3, 0]
except IndexError as e:
print(e) # index 3 is out of bounds for axis 0 with size 3Slices never raise this error. They clip silently, so a[:, 10:] returns an empty array instead of failing. An unexpected empty result is a sign that a slice bound is wrong.
A debugging routine
When a selection gives a wrong or surprising result, work through these checks in order.
The checks use these tools:
arr.shapeandresult.shapeshow whether an axis was dropped or reordered.mask.sum()counts the selected elements, andmask.dtypeshould bebool.np.shares_memory(a, b)tells you whether two arrays overlap.result.base is Noneis a quick hint that the result owns its data.- A small
np.arange(12).reshape(3, 4)array makes every element identifiable by its value.
Summary table
| Symptom | Likely cause | Fix |
|---|---|---|
| `ValueError: truth value ... ambiguous` | Missing parentheses, or `and`/`or` used | `(x > 0) & (y < 3)` |
| Assignment has no effect | Chained indexing on a copy | One index expression, or `np.flatnonzero` |
| Result has fewer dimensions | Integer index dropped an axis | Use `i:i+1` |
| Dimensions in unexpected order | Array indices separated by a slice | Check `.shape`, split into steps |
| `IndexError` on a mask | Mask length differs from axis length | Build the mask from the same axis |
Exercise
You run a[a > 5][1] = 0 on an integer array and find that a is unchanged. Why, and how do you set the second element above 5 to zero?
Show answer
a[a > 5] is a boolean-mask selection, which returns a copy. The assignment modifies that temporary copy. Compute the positions with idx = np.flatnonzero(a > 5) (for a 2-D array use np.argwhere or np.nonzero) and assign with a.flat[idx[1]] = 0, or for a 1-D array a[idx[1]] = 0.