Concept Flow - Boolean indexing
Start with array
Create boolean mask
Apply mask to array
Get filtered array
Use filtered array for analysis or output
Boolean indexing uses a mask of True/False values to select elements from an array.
import numpy as np arr = np.array([10, 15, 20, 25, 30]) mask = arr > 20 filtered = arr[mask] print(filtered)
| Step | Action | Array 'arr' | Mask 'mask' | Filtered array 'filtered' |
|---|---|---|---|---|
| 1 | Create array | [10, 15, 20, 25, 30] | N/A | N/A |
| 2 | Create mask arr > 20 | [10, 15, 20, 25, 30] | [False, False, False, True, True] | N/A |
| 3 | Apply mask to arr | [10, 15, 20, 25, 30] | [False, False, False, True, True] | [25, 30] |
| 4 | Print filtered | [10, 15, 20, 25, 30] | [False, False, False, True, True] | [25, 30] |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| arr | N/A | [10, 15, 20, 25, 30] | [10, 15, 20, 25, 30] | [10, 15, 20, 25, 30] | [10, 15, 20, 25, 30] |
| mask | N/A | N/A | [False, False, False, True, True] | [False, False, False, True, True] | [False, False, False, True, True] |
| filtered | N/A | N/A | N/A | [25, 30] | [25, 30] |
Boolean indexing in numpy: - Create a boolean mask by comparing array elements. - Use mask to select elements: filtered = arr[mask] - Mask is same shape as array, with True/False. - Result is array of elements where mask is True. - Useful for filtering data easily.
numpy allow you to do?arr using boolean indexing?import numpy as np arr = np.array([2, 7, 4, 9, 1]) result = arr[arr % 2 == 1]
import numpy as np arr = np.array([1, 2, 3, 4]) mask = arr > 2 print(arr[mask == True])
data = np.array([10, 15, 20, 25, 30]), how can you select elements greater than 12 and less than 28 using boolean indexing?data[(data > 12) & (data < 28)] correctly uses & (element-wise AND) with parentheses around each condition. Using Python keywords and/or cause errors because they don't work element-wise on arrays. Using | (bitwise OR) selects elements greater than 12 or less than 28, which is wrong here.Pass the test and this pattern moves unknown