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.
import numpy as np
arr = np.array([1, -2, 3, -4, 5])
positives = arr[arr > 0]
print(positives)2Practical Example
Here is a real-world application of Boolean Indexing showing how it is used in production NumPy code.
import numpy as np
arr = np.array([10, -5, 20, -15, 30])
arr[arr < 0] = 0
print(arr)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.
import numpy as np
arr = np.array([1, -2, 3, -4, 5])
positives = arr[arr > 0]
print(positives)