0Pricing
Pandas & NumPy Academy · Lesson

Boolean Masking and Fancy Indexing

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

Boolean Masking and Fancy Indexing is a free Pandas & NumPy Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Pandas & NumPy Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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]

Modifying Values with Boolean Indexing

You can assign straight to a boolean selection, changing only the matching elements in place. It's the fastest way to cap outliers or fill in missing values.

import numpy as np

a = np.array([5, -3, 8, -1, 2, -7])
a[a < 0] = 0    # zero out negatives in-place
print(a)        # [5 0 8 0 2 0]

# Cap values above 6
a[a > 6] = 6
print(a)        # [5 0 6 0 2 0]

Boolean Masking on 2-D Arrays

A boolean mask on a 2-D array always returns a flat 1-D result. To select whole rows, build a 1-D mask from one column and index along axis 0.

import numpy as np

m = np.array([[1, 5], [3, 2], [8, 4], [6, 7]])
# Select rows where first column > 4
mask = m[:, 0] > 4
print(mask)     # [False False  True  True]
print(m[mask])  # [[8 4] [6 7]]

np.where with Masks

np.where(condition, x, y) keeps the array's shape: it picks x where the condition holds and y elsewhere. Perfect for swapping values without flattening.

import numpy as np

a = np.array([3, -1, 5, -2, 4])
result = np.where(a >= 0, a, 0)  # keep positives, replace negatives
print(result)  # [3 0 5 0 4]

# Recode: above-average -> 'high', else -> 'low'
labels = np.where(a >= a.mean(), 'high', 'low')
print(labels)  # ['high' 'low' 'high' 'low' 'high']

Fancy Indexing Basics

Fancy indexing means passing an array of integer indices to grab specific elements — in any order, with repeats. It always returns a copy.

import numpy as np

a = np.array([10, 20, 30, 40, 50])
idx = np.array([4, 1, 1, 3])
print(a[idx])   # [50 20 20 40]

# 2D index shape -> 2D output
idx2d = np.array([[0, 2], [4, 1]])
print(a[idx2d])  # [[10 30] [50 20]]

Fancy Indexing on 2-D Arrays

On a 2-D array, paired index arrays pick scattered points: m[rows, cols] grabs the element at each (row, col) pair, not a whole sub-matrix.

import numpy as np

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

# Select elements at (0,2), (1,0), (2,1)
rows = [0, 1, 2]
cols = [2, 0, 1]
print(m[rows, cols])  # [3 4 8]

np.ix_ for Row-Column Grid Selection

np.ix_ selects a sub-matrix at every combination of the rows and columns you list — handy when you want many rows AND many columns, not just pairs.

import numpy as np

m = np.arange(16).reshape(4, 4)
print(m)

# Select rows 0,2 and columns 1,3
ix = np.ix_([0, 2], [1, 3])
print(m[ix])
# [[ 1  3]
#  [ 9 11]]

np.nonzero() and np.argwhere()

np.nonzero returns the indices of non-zero (or True) elements as a tuple per axis. np.argwhere gives the same info stacked as easy-to-read rows.

import numpy as np

a = np.array([0, 3, 0, 5, 0, 7])
print(np.nonzero(a))       # (array([1, 3, 5]),)
print(np.argwhere(a > 0))  # [[1] [3] [5]]

Combining Boolean and Fancy Indexing

Mix the two: use a boolean mask to filter rows, then fancy indexing to reorder columns. Together they filter and rearrange data in one clean step.

import numpy as np

data = np.array([[1, 2, 3],
                 [4, 5, 6],
                 [7, 8, 9]])
scores = np.array([0.9, 0.3, 0.8])

# Keep high-scoring rows, reorder columns to [2, 0, 1]
high = data[scores > 0.5]
reordered = high[:, [2, 0, 1]]
print(reordered)

Performance: Boolean vs Fancy Indexing

Both boolean and fancy indexing return copies. For filtering, a boolean mask is usually the most readable and plenty fast — a great default.

import numpy as np

a = np.random.rand(1_000_000)

# Boolean mask -- readable and fast
result = a[a > 0.5]
print('filtered size:', result.size)  # ~500000

# Equivalent with np.where + fancy index
idx = np.where(a > 0.5)[0]
result2 = a[idx]
print('same result:', np.array_equal(result, result2))

Quick Check

Test your understanding of boolean masking and fancy indexing from this lesson.

Lesson Recap

Well done! Boolean masks filter and copy, np.where keeps the array's shape, and fancy indexing grabs any elements you name. Next: Pandas Series!

Frequently asked questions

Is the “Boolean Masking and Fancy Indexing” lesson free?

Yes — the full text of “Boolean Masking and Fancy Indexing” is free to read here on the web, and the Pandas & NumPy Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Pandas & NumPy Academy course, upgrade to CoddyKit PRO.

What will I learn in “Boolean Masking and Fancy Indexing”?

Filter arrays with boolean conditions and select arbitrary elements using integer index arrays. You practise Pandas & NumPy Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Pandas & NumPy Academy?

No prior experience is required. Pandas & NumPy Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Boolean Masking and Fancy Indexing” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Pandas & NumPy Academy lesson?

Yes. Every Pandas & NumPy Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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