Sub topic 12
Common pitfalls and how to debug them
This chapter collects the mistakes that cause most NumPy indexing bugs. It assumes you can create arrays with np.array, np.arange, and reshape, and that you know what shape and dtype mean. It also assumes you have met integer indexing, slices, boolean masks, and fancy indexing in the earlier chapters. Here you will learn to recognize each failure, explain it, and fix it.
Pitfall 1: operator precedence and Python's `and`/`or`
Python's and, or, and not ask for one truth value from each operand. An array with many elements has no single truth value, so NumPy raises an error. The element-wise operators are &, |, and ~.
These operators also bind more tightly than comparisons such as > and ==. Without parentheses, Python groups the expression differently from what you intended.
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(e) # The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
try:
data[(data > 0) and (data % 2 == 0)]
except ValueError as e:
print("and fails too:", type(e).__name__)
print(data[(data > 0) & (data % 2 == 0)]) # [4 2]In the first expression, 0 & data % 2 is evaluated first. The remaining comparisons are then chained, and Python needs a single truth value from an array. The error message points at and, but the real cause is the missing parentheses.
Rule: wrap every comparison in parentheses before you combine it with & or |.
`~` works on booleans, not on integers
On a boolean array, ~ flips each element. On an integer array, it flips every bit, so ~1 is -2, not 0. If a mask has been converted to integers, ~ gives you numbers that are not a mask.
import numpy as np
flags = np.array([1, 0, 1])
print(~flags) # [-2 -1 -2]
print(~flags.astype(bool)) # [False True False]Pitfall 2: a mask that became integers
A boolean array selects by position in a mask. An integer array selects by index. If you convert a mask with astype(int), the same values mean something else.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
m = (data > 0).astype(int) # [1 0 1 0 0 1]
print(data[m]) # [-1 4 -1 4 4 -1]
print(data[m.astype(bool)]) # [4 7 2]The integer version treats each 1 or 0 as an index into data. It does not raise an error, which is why this bug is easy to miss. If the result is the same length as the mask but contains repeated values, check the mask's dtype.
Pitfall 3: assigning through a copy
Basic slices return views, so assigning through them changes the original. Fancy indexing and boolean masks return copies. A chained expression such as a[mask][0] = 100 first builds a copy with a[mask], then writes into that copy. The write is lost, and NumPy does not warn you.
import numpy as np
a = np.arange(12).reshape(3, 4)
a[a[:, 0] > 0][0] = 100 # writes into a temporary copy
print(a[1, 0]) # 4, unchanged
a[a[:, 0] > 0, 0] = 100 # one indexing step, so it writes into a
print(a)
# [[ 0 1 2 3]
# [100 5 6 7]
# [100 9 10 11]]The fix is to put the whole selection in a single index expression on the left side of =. The reverse problem also occurs. If you expect a copy but receive a view, edits leak into the source array. Call .copy() when you need independence.
Pitfall 4: repeated indices and augmented assignment
With fancy indexing, a[idx] += 1 is evaluated as read, add, write. If idx contains the same position twice, both reads see the original value, so only one increment survives.
import numpy as np
counts = np.zeros(3, dtype=int)
counts[[0, 0, 1]] += 1
print(counts) # [1 1 0]
counts = np.zeros(3, dtype=int)
np.add.at(counts, [0, 0, 1], 1)
print(counts) # [2 1 0]Use np.add.at for unbuffered accumulation. This matters when you build histograms or counts by hand.
Pitfall 5: shape surprises
Many indexing bugs come from a result whose shape is not what you assumed. Three situations cause most of them.
Integers drop an axis, and lists keep it
An integer index removes the axis. A slice of length one or a list keeps it. This matters in broadcasting.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[:, 0].shape) # (3,)
print(a[:, 0:1].shape) # (3, 1)
print(a[:, [0]].shape) # (3, 1)
print(a[:, 0, np.newaxis].shape) # (3, 1)
try:
a - a[:, 0] # (3, 4) minus (3,)
except ValueError:
print("broadcast error")
print(a - a[:, [0]]) # subtract each row's first value
# [[0 1 2 3]
# [0 1 2 3]
# [0 1 2 3]]Arrays separated by a slice move to the front
When a fancy index and an integer are separated by a slice, NumPy cannot decide where the combined axis belongs. It places the indexed axis first.
import numpy as np
b = np.arange(24).reshape(2, 3, 4)
print(b[0, :, [1, 2]].shape) # (2, 3)
print(b[0][:, [1, 2]].shape) # (3, 2)
print(b[0, :, 1:3].shape) # (3, 2)In the first line, the 0 and the list [1, 2] act together as advanced indices. The slice between them splits them, so the new axis of length 2 comes first. If you want the layout (3, 2), split the indexing into two steps, or use a slice instead of a list.
Boolean masks over a whole array return 1-D
A mask with the same shape as the array picks individual elements, so the 2-D structure is lost. A 1-D mask that matches only the first axis picks whole rows and keeps the columns.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[a > 5].shape) # (6,)
print(a[a[:, 0] > 0].shape) # (2, 4)To keep the shape and change only some values, use np.where(a > 5, a, 0), which returns an array the same shape as a.
Pitfall 6: out-of-range and mismatched indices
Integer indices that are out of range raise IndexError. Slices never do: they clip silently. This makes slice bugs harder to find.
import numpy as np
x = np.arange(5)
print(x[3:100]) # [3 4]
print(x[10:20]) # [] (empty, no error)
print(x[4:0:-1]) # [4 3 2 1] (stop is excluded, so 0 is missing)
print(x[::-1]) # [4 3 2 1 0]
try:
x[5]
except IndexError as e:
print(e) # index 5 is out of bounds for axis 0 with size 5A reversed slice such as x[4:0:-1] stops before index 0. To include the first element, leave the stop empty: x[4::-1], or just use x[::-1].
A boolean mask must match the length of the axis it indexes. A mask of the wrong length raises an IndexError that names the two sizes. Check the shapes of the mask and the array if you see it.
Fancy indices must be integers. A float array used as an index raises an IndexError. Convert it with astype(int) only if truncation is what you want.
A symptom table
| Symptom | Likely cause | Fix | Column |
|---|---|---|---|
| `ValueError: truth value ... ambiguous` | `and`, `or`, or `not` on arrays, or a missing parenthesis | Use `&`, `\ | `, `~` and wrap each comparison in parentheses |
| Selection returns repeated or odd values | Mask converted to integers | Keep the mask boolean, or call `.astype(bool)` | |
| Assignment has no effect | Chained indexing wrote into a copy | Use one index expression on the left of `=` | |
| Edit changes the original unexpectedly | Slice returned a view | Call `.copy()` | |
| `+=` counts too little | Repeated fancy indices | Use `np.add.at` | |
| Broadcast error after taking a column | Integer index dropped an axis | Use `a[:, [0]]`, `a[:, 0:1]`, or `np.newaxis` | |
| Shape has the indexed axis first | Fancy index and integer separated by a slice | Index in two steps | |
| Result is 1-D when you expected 2-D | Full-shape mask | Use a row mask or `np.where` | |
| Slice returns an empty array | Slice clipped without error | Print `len` and bounds before slicing |
A debugging routine
Most indexing bugs show up as soon as you print three facts about the result: its shape, its dtype, and whether it shares memory with the source. The helper below does this.
import numpy as np
def describe(name, x, base):
print(f"{name}: shape={x.shape} dtype={x.dtype} "
f"shares_memory={np.shares_memory(x, base)}")
a = np.arange(12).reshape(3, 4)
describe("a[1]", a[1], a) # shape=(4,) shares_memory=True
describe("a[:, :2]", a[:, :2], a) # shape=(3, 2) shares_memory=True
describe("a[[0, 1]]", a[[0, 1]], a) # shape=(2, 4) shares_memory=False
describe("a[a > 5]", a[a > 5], a) # shape=(6,) shares_memory=FalseThe dtype shown is int64 on most platforms. Use np.shares_memory to test for views. The .base attribute is less reliable, because results of reshape also have a base even though no one thinks of them as slices.
Summary of habits
- Parenthesize each comparison, and use
&,|,~on arrays. - Keep masks boolean and indices integer.
- Put the whole selection in a single index expression when assigning.
- Know which operations return views (basic slices) and which return copies (fancy indexing, masks).
- Print shape, dtype, and
np.shares_memorybefore guessing.
Exercise
The code below is meant to set every negative value in the second column of a to 0, but a is unchanged afterward. Explain why, and rewrite the last line so it works.
a = np.array([[1, -2], [-3, 4], [5, -6]])
col = a[:, 1]
a[a[:, 1] < 0][:, 1] = 0
Show answer
The expression a[a[:, 1] < 0] uses a boolean mask, so it returns a copy of the matching rows. The [:, 1] = 0 then writes into that copy, and a keeps its values. Use a single index expression: a[a[:, 1] < 0, 1] = 0. The mask picks the rows and the integer 1 picks the column, in one assignment on a itself. (Also, col = a[:, 1] is a view, so col[col < 0] = 0 would work too.)
Exercise
Given b = np.arange(24).reshape(2, 3, 4), what is the shape of b[1, :, [0, 3]], and how can you get shape (3, 2) instead?
Show answer
The shape is (2, 3). The integer 1 and the list [0, 3] are both advanced indices, and the slice between them separates them, so NumPy puts the indexed axis first. To get (3, 2), index in two steps: b[1][:, [0, 3]].