Sub topic 3
Modifying Values with NumPy Masks and Indexing
Assume you know Python lists, NumPy arrays, shape, dtype, np.array, np.arange, and reshape. This chapter focuses on changing selected values and understanding shape changes.
Modifying Values Through Masks and `np.where`
A Boolean mask is an array of True and False values. Use it on the left side of assignment to modify matching elements. np.where instead creates a new array by choosing between two values.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
data[data < 0] = 0
print(data) # [4 0 7 0 0 2]
labels = np.where(data >= 5, "high", "low")
print(labels) # ['low' 'low' 'high' 'low' 'low' 'low']Combine conditions with & and |. Put every comparison in parentheses.
Fancy Indexing with Integer Arrays
Fancy indexing uses integer arrays to select arbitrary positions. Two index arrays pair positions element by element:
a = np.arange(12).reshape(3, 4)
print(a[[0, 2], [1, 3]]) # [1 11]This selects (row 0, column 1) and (row 2, column 3). A one-dimensional row index selects whole rows:
print(a[[0, 2]])
# [[ 0 1 2 3]
# [ 8 9 10 11]]Fancy indexing returns a copy, so changing the result does not change a.
Selecting Blocks with `np.ix_`
Use np.ix_ when you want every combination of selected rows and columns:
block = a[np.ix_([0, 2], [1, 3])]
print(block)
# [[ 1 3]
# [ 9 11]]Mixing Index Types
Slices preserve dimensions, while an integer removes that axis. Masks can select rows:
print(a[1, 1:3]) # [5 6]
print(a[a[:, 0] > 0]) # rows whose first value is positiveCommon Pitfalls and Debugging
- Check
a.shapeafter mixed indexing. - Use parentheses around each comparison.
- Remember that basic slices usually share memory; use
.copy()when independence matters. - Use
np.shares_memory(x, y)to test whether two arrays share storage.
Exercise
Which expression selects rows 0 and 2 together with columns 1 and 3 as a rectangular block?
Show answer
a[np.ix_([0, 2], [1, 3])].