🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEnumpy

numpy Documentation

LOADING ENGINE...

Boolean Indexing

AI & DATA SCIENCE // boolean-indexing

Boolean indexing selects elements from an array using another array (or expression) of True/False values of the same shape, keeping only the elements where the corresponding value is True.

Syntax

arr[boolean_condition]

Deep Dive Course

Writing a condition like arr > 5 inside the brackets first evaluates it into a boolean array the same shape as arr, then uses that boolean array to select only the elements at positions where it's True, returning them as a flattened 1D array regardless of the original array's dimensionality. Unlike basic slicing, boolean indexing always returns a copy, since the selected elements generally aren't contiguous in memory and can't be represented as a simple view. It's the standard way to filter or conditionally modify array elements without writing an explicit Python loop.

1Understanding Boolean Indexing

Writing a condition like arr > 5 inside the brackets first evaluates it into a boolean array the same shape as arr, then uses that boolean array to select only the elements at positions where it's True, returning them as a flattened 1D array regardless of the original array's dimensionality. Unlike basic slicing, boolean indexing always returns a copy, since the selected elements generally aren't contiguous in memory and can't be represented as a simple view. It's the standard way to filter or conditionally modify array elements without writing an explicit Python loop.

💡

Boolean indexing also works on the left side of an assignment, e.g. setting all elements matching a condition to 0, which is the idiomatic, vectorized way to conditionally replace elements without looping.

editor.html
import numpy as np

arr = np.array([1, -2, 3, -4, 5])
positives = arr[arr > 0]
print(positives)
localhost:3000

2Practical Example

Here is a real-world application of Boolean Indexing showing how it is used in production NumPy code.

editor.html
import numpy as np

arr = np.array([10, -5, 20, -15, 30])
arr[arr < 0] = 0
print(arr)
localhost:3000

3Best Practices

Follow these guidelines when working with Boolean Indexing:

1. Use boolean indexing to filter or conditionally modify elements instead of writing an explicit Python for loop with an if check

2. Combine multiple conditions with & and |, not Python's and/or, which don't work element-wise on arrays, wrapping each condition in parentheses

3. Remember boolean indexing always returns a copy, so modifying the result never affects the original array

⚠️

Tip: Boolean indexing also works on the left side of an assignment, e.g. setting all elements matching a condition to 0, which is the idiomatic, vectorized way to conditionally replace elements without looping.

editor.html
import numpy as np

arr = np.array([1, -2, 3, -4, 5])
positives = arr[arr > 0]
print(positives)
localhost:3000

Examples

Example 01Basic Usage
import numpy as np

arr = np.array([1, -2, 3, -4, 5])
positives = arr[arr > 0]
print(positives)
Example 02Advanced Example
import numpy as np

arr = np.array([10, -5, 20, -15, 30])
arr[arr < 0] = 0
print(arr)

Best Practices

  • Use boolean indexing to filter or conditionally modify elements instead of writing an explicit Python for loop with an if check
  • Combine multiple conditions with & and |, not Python's and/or, which don't work element-wise on arrays, wrapping each condition in parentheses
  • Remember boolean indexing always returns a copy, so modifying the result never affects the original array

Interview Question

Why does combining two conditions with Python's `and` operator on whole arrays raise an error, and what should you write instead?

Hint: Think about what Python's `and` operator actually does with a whole array.

Python's and operator is designed to evaluate a single boolean truth value on each side, but a NumPy array with more than one element doesn't have one unambiguous truth value, so trying to use it with and raises a ValueError about the truth value of an array being ambiguous. The correct approach is to use the bitwise & operator instead, which works element-wise across the whole array, combined with parentheses around each condition due to operator precedence.

Exercises

MediumPractice using Boolean Indexing in a real scenario.
View Solution
import numpy as np

arr = np.array([1, -2, 3, -4, 5])
positives = arr[arr > 0]
print(positives)

Frequently Asked Questions

Why does combining two conditions with Python's `and` operator on whole arrays raise an error, and what should you write instead?

Python's and operator is designed to evaluate a single boolean truth value on each side, but a NumPy array with more than one element doesn't have one unambiguous truth value, so trying to use it with and raises a ValueError about the truth value of an array being ambiguous. The correct approach is to use the bitwise & operator instead, which works element-wise across the whole array, combined with parentheses around each condition due to operator precedence.

Related Functions

basic-slicingfancy-indexingnp-where