Sub topic 2
Views, Copies, and Boolean Masks in NumPy
Assume you know basic Python lists, NumPy array creation, shape, and dtype. NumPy indexing can either expose existing data or create new data. This difference matters when you modify a result.
Views versus copies: when slicing shares memory
A view is a new array object that refers to the original array's memory. Basic slicing usually creates a view. Changes through the view therefore change the source array. Use .copy() when the selection must be independent.
import numpy as np
a = np.arange(12).reshape(3, 4)
view = a[:, :2]
view[0, 0] = 99
print(a[0, 0]) # 99
independent = a[:, :2].copy()
independent[0, 0] = -1
print(a[0, 0]) # 99
rows = a[[0, 1]] # integer-array indexing creates a copy
rows[0, 0] = -5
print(a[0, 0]) # 99
print(np.shares_memory(a, view)) # True| Operation | Typical result | Shares memory? |
|---|---|---|
| `a[1:, :2]` | Basic slice | Yes |
| `a[[0, 1]]` | Fancy indexing | No |
| `a[a > 0]` | Boolean indexing | No |
| `a[1:, :2].copy()` | Explicit copy | No |
Boolean masks: filtering with conditions
A boolean mask is an array of True and False values. NumPy uses it to select matching elements. Boolean indexing returns a new one-dimensional array.
data = np.array([4, -1, 7, 0, -5, 2])
mask = data > 0
print(mask) # [ True False True False False True]
print(data[mask]) # [4 7 2]
data[data < 0] = 0 # assignment changes data directly
print(data) # [4 0 7 0 0 2]Combining conditions with `&`, `|`, and `~`
Use & for “and,” | for “or,” and ~ for “not.” Put each comparison in parentheses. Python's operator precedence can otherwise produce an error or an unintended mask.
data = np.array([4, -1, 7, 0, -5, 2])
even_positive = (data > 0) & (data % 2 == 0)
print(data[even_positive]) # [4 2]
outside = (data < 0) | (data > 5)
print(data[outside]) # [-1 7 -5]
print(data[~(data > 0)]) # [-1 0 -5]
print(np.where(data > 0, data, -1)) # [ 4 -1 7 -1 -1 2]Exercise
What does a[(a > 2) & (a < 6)] do, and why are parentheses needed?
Show answer
It selects values greater than 2 and less than 6. Parentheses ensure each comparison is evaluated before the elementwise &.