Lecture

Boolean Masking and Filtering

NumPy lets you filter arrays using boolean conditions, a technique known as masking.

When you compare elements in an array, NumPy returns a new array containing only the values that satisfy the condition.


Boolean Arrays

A comparison such as arr > 10 generates a new array of boolean valuesTrue or False.

Boolean Arrays
arr = np.array([5, 12, 18, 7]) mask = arr > 10 print(mask) # [False True True False]

Filtering Values

You can use this boolean array as a mask to filter the original array.

Filtering Values
print(arr[mask]) # [12 18]

Or write it more directly:

Filtering Values another way
print(arr[arr > 10]) # [12 18]

Masking is especially useful for filtering rows, selecting ranges, or identifying outliers.


Summary

  • Use comparisons (>, <, ==, etc.) to create boolean masks
  • Apply the mask to select only the values you want
  • Works with both 1D and 2D arrays
Quiz
0 / 1

Boolean masking allows you to filter NumPy arrays based on conditions.

True
False

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help