Introduction
Boolean masking helps you pick out only the data you want from a big set. It makes finding and working with specific parts easy and fast.
Jump into concepts and practice - no test required
Boolean masking helps you pick out only the data you want from a big set. It makes finding and working with specific parts easy and fast.
masked_array = original_array[boolean_condition]
import numpy as np arr = np.array([10, 20, 30, 40, 50]) mask = arr > 25 filtered = arr[mask] print(filtered)
import numpy as np arr = np.array([5, 15, 25, 35, 45]) filtered = arr[arr % 2 == 1] print(filtered)
This program shows how to find temperatures below zero using boolean masking. It prints the original temperatures, the mask of True/False for cold days, and the filtered cold temperatures.
import numpy as np # Create an array of temperatures in Celsius temps = np.array([22, -5, 15, 0, -10, 30, 5]) # Create a mask for temperatures below zero cold_days = temps < 0 # Use boolean masking to get only cold days cold_temps = temps[cold_days] print("All temperatures:", temps) print("Cold days mask:", cold_days) print("Temperatures below zero:", cold_temps)
Boolean masks must be the same shape as the array you want to filter.
Boolean masking is very fast and works well with large data sets.
You can combine multiple conditions using & (and) and | (or) with parentheses.
Boolean masking helps select specific data easily.
It uses True/False arrays to pick elements.
It is useful for filtering and analyzing data quickly.
numpy?arr to select values greater than 5?>.mask = arr > 5 creates a boolean array where True means element > 5.import numpy as np arr = np.array([2, 7, 4, 9, 1]) mask = arr > 4 result = arr[mask]
result?arr[mask] selects elements where mask is True: [7, 9].import numpy as np arr = np.array([1, 3, 5, 7]) mask = arr > 4 print(arr[mask])
arr > 4 creates a boolean array of same length as arr without error.arr[mask] selects elements > 4 without error.data = np.array([10, 0, 5, -3, 8]). You want to select only positive numbers excluding zero using boolean masking. Which code correctly achieves this?data > 0.data[data > 0] selects 10, 5, and 8, excluding zero and negatives.