Array Masking and Filtering

Python

Masking and Filtering Arrays with NumPy

Array masking allows you to select elements based on conditions or boolean arrays.

Example: Boolean Masking

import numpy as np

a = np.array([True, True, True, False, False])
b = np.array([[1, 2, 3, 4, 5],
              [1, 2, 3, 4, 5]])

filtered = b[:, a]
print(filtered)
# Output:
# [[1 2 3]
#  [1 2 3]]

Example: Masking with Conditions

x = np.array([1, 2, 3, 4, 5])
mask = x > 2
print(x[mask])  # Output: [3 4 5]

Tips

  • The mask must be a boolean array of the same length as the dimension being indexed.
  • You can combine conditions using & (and), | (or), and ~ (not), e.g., (x > 2) & (x < 5).

References