Arrays - selecting

NumPy - The Basics

1 min read

Published Sep 22 2025


11
0
0
0

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:

  1. A condition is applied to the array → produces a boolean mask.
  2. The boolean mask is used to select only the True elements.
  3. You can combine multiple conditions with parentheses to create complex selection logic.

Examples:

import numpy as np

arr = np.array([1, 3, 5, 7, 9, 12, 17, 20])

# Single condition
print("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 combination
print("arr > 5 AND (arr < 10 OR arr == 17):", arr[(arr > 5) & ((arr < 10) | (arr == 17))])
# → [7 9 17]

# Boolean mask stored separately
mask = (arr % 2 == 0) & (arr > 5)
print("Even numbers greater than 5:", arr[mask])
# → [12 20]

Products from our shop

Docker Cheat Sheet - Print at Home Designs

Docker Cheat Sheet - Print at Home Designs

Docker Cheat Sheet Mouse Mat

Docker Cheat Sheet Mouse Mat

Docker Cheat Sheet Travel Mug

Docker Cheat Sheet Travel Mug

Docker Cheat Sheet Mug

Docker Cheat Sheet Mug

Vim Cheat Sheet - Print at Home Designs

Vim Cheat Sheet - Print at Home Designs

Vim Cheat Sheet Mouse Mat

Vim Cheat Sheet Mouse Mat

Vim Cheat Sheet Travel Mug

Vim Cheat Sheet Travel Mug

Vim Cheat Sheet Mug

Vim Cheat Sheet Mug

SimpleSteps.guide branded Travel Mug

SimpleSteps.guide branded Travel Mug

Developer Excuse Javascript - Travel Mug

Developer Excuse Javascript - Travel Mug

Developer Excuse Javascript Embroidered T-Shirt - Dark

Developer Excuse Javascript Embroidered T-Shirt - Dark

Developer Excuse Javascript Embroidered T-Shirt - Light

Developer Excuse Javascript Embroidered T-Shirt - Light

Developer Excuse Javascript Mug - White

Developer Excuse Javascript Mug - White

Developer Excuse Javascript Mug - Black

Developer Excuse Javascript Mug - Black

SimpleSteps.guide branded stainless steel water bottle

SimpleSteps.guide branded stainless steel water bottle

Developer Excuse Javascript Hoodie - Light

Developer Excuse Javascript Hoodie - Light

Developer Excuse Javascript Hoodie - Dark

Developer Excuse Javascript Hoodie - Dark

© 2025 SimpleSteps.guide
AboutFAQPoliciesContact