Arrays - selecting
NumPy - The Basics
1 min read
This section is 1 min read, full guide is 14 min read
Published Sep 22 2025, updated Aug 17 2026
11
Show sections list
0
Log in to enable the "Like" button
0
Guide comments
0
Log in to enable the "Save" button
Respond to this guide
Guide Sections
Guide Comments
NumPyPython
Boolean Indexing with Conditions
- Boolean indexing selects array elements that satisfy a condition.
- The condition returns a boolean array (
True/False) of the same shape. - Use logical operators to combine multiple conditions:
&- logical AND|- logical OR~- logical NOT- Parentheses are required around each condition when combining with
&or|. - The result is a 1D array of elements where the condition(s) is
True.
How it works:
- A condition is applied to the array → produces a boolean mask.
- The boolean mask is used to select only the
Trueelements. - You can combine multiple conditions with parentheses to create complex selection logic.
Examples:
import numpy as nparr = np.array([1, 3, 5, 7, 9, 12, 17, 20])# Single conditionprint("arr < 7:", arr[arr < 7]) # → [1 3 5]# Multiple conditions (AND)print("arr > 4 AND arr <= 17:", arr[(arr > 4) & (arr <= 17)]) # → [5 7 9 12 17]# Multiple conditions (OR)print("arr <=2 OR arr > 18 OR arr == 9:", arr[((arr <= 2) | (arr > 18)) | (arr == 9)]) # → [1 9 20]# Negation (NOT)print("NOT (arr < 10):", arr[~(arr < 10)]) # → [12 17 20]# Complex combinationprint("arr > 5 AND (arr < 10 OR arr == 17):", arr[(arr > 5) & ((arr < 10) | (arr == 17))]) # → [7 9 17]# Boolean mask stored separatelymask = (arr % 2 == 0) & (arr > 5)print("Even numbers greater than 5:", arr[mask]) # → [12 20]