0Pricing
Pandas & NumPy Academy · Lesson

Boolean Masking and Fancy Indexing

Filter arrays with boolean conditions and select arbitrary elements using integer index arrays.

Boolean Arrays as Masks

A boolean mask is an array of True/False values. Use it as an index and you keep only the elements marked True — your main filtering tool.

import numpy as np

a = np.array([5, 3, 8, 1, 9, 2, 7])
mask = a > 4
print(mask)       # [ True False  True False  True False  True]
print(a[mask])    # [5 8 9 7]

Compound Boolean Conditions

Build compound filters with & (and), | (or), and ~ (not). Always wrap each condition in parentheses, or precedence will trip you up.

import numpy as np

a = np.array([3, 7, 2, 9, 1, 6, 4, 8])

# Elements between 4 and 8 inclusive
result = a[(a >= 4) & (a <= 8)]
print(result)   # [7 6 4 8]

# Elements less than 3 or greater than 7
result2 = a[(a < 3) | (a > 7)]
print(result2)  # [2 9 1 8]

All lessons in this course

  1. Universal Functions (ufuncs)
  2. Aggregation Functions
  3. Broadcasting Rules
  4. Boolean Masking and Fancy Indexing
← Back to Pandas & NumPy Academy