True and False values. In a quant workflow, a mask can retain eligible instruments, finite observations or scenarios that breach a limit. The condition defines the sample: a statistic computed after filtering describes the retained observations.True, preserving their order. It is a form of advanced array indexing.From a condition to a selection
These fictional prices are USD per share. Retain prices strictly above 100:
import numpy as np
prices = np.array([98, 101, 105, 99])
mask = prices > 100
selected = prices[mask]
print(mask.tolist())
# [False, True, True, False]
print(selected.tolist())
# [101, 105]
print(int(selected.sum()))
# 206The comparison creates the mask; the brackets perform the selection. Positions 1 and 2 survive, using Python's zero-based indexing. Their prices sum to 206; this is a selection check, not a portfolio valuation.
Original deterministic illustration. Prices are stipulated USD per share; the threshold is strictly greater than 100. The mask and prices share the same observation order.
Reading a selection and assigning through a mask
import numpy as np
prices = np.array([98, 101, 105, 99])
mask = prices > 100
selected = prices[mask]
selected[0] = 0
print(prices.tolist())
# [98, 101, 105, 99]
print(selected.tolist())
# [0, 105]
prices[mask] = 0
print(prices.tolist())
# [98, 0, 0, 99]prices[mask][0] = 0 instead changes a temporary selection copy and leaves prices unchanged.A valid shape can still select the wrong observations
import numpy as np
prices = np.array([98, 101, 105, 99])
mask = prices > 100
reordered = np.sort(prices)
print(reordered.tolist())
# [98, 99, 101, 105]
print(reordered[mask].tolist())
# [99, 101]
print(reordered[reordered > 100].tolist())
# [101, 105]The stale mask still selects positions 1 and 2, even though their contents changed. Recompute the condition after reordering, or move the observations and their mask together. The same discipline applies when using a price-derived mask on a separate array of positions: both arrays must describe the same instruments in the same order.
Combine conditions explicitly
& for elementwise AND, | for OR and ~ for complement. For example, (prices > 100) & (prices <= 103) retains only 101 from the original prices. Python's and, or and not attempt a truth test of the whole array; a multi-element NumPy array raises an ambiguous-truth-value error.np.isfinite(values) builds a mask that excludes both NaN and positive or negative infinity. A threshold test by itself does not establish data validity.Sources
- NumPy: Indexing on ndarrays, especially “Boolean array indexing” and “Assigning values to indexed arrays”.
- NumPy: Copies and views, especially the distinction between advanced-index selection and assignment.
- NumPy: Logic functions, for elementwise predicates and finite-value tests.