Conditional Selection
Conditional selection lets you filter arrays based on criteria. Think of it like searching for contacts who live in a specific city. NumPy makes this super efficient.
Boolean Indexing
Use boolean arrays to select elements.
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
mask = arr > 25
print(f"Original: {arr}")
print(f"Mask: {mask}")
print(f"Filtered: {arr[mask]}")
The mask is a boolean array. arr[mask] returns only the True values.
np.where - The Ternary Operator
np.where(condition, x, y) returns x where condition is True, y otherwise.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
result = np.where(arr > 3, 'big', 'small')
print(f"Values: {arr}")
print(f"Labels: {result}")
Here is the thing - np.where doesn't modify the original array. It returns a new array with the specified values.
Combining Conditions
Use np.logical_and, np.logical_or for multiple conditions.
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
mask = np.logical_and(arr > 3, arr < 7)
print(f"Values: {arr}")
print(f"Between 4 and 6: {arr[mask]}")
One thing that confused me at first was why we can't use and/or keywords. That's because Python's and/or work on single values, not arrays.
Try it Yourself →Key Takeaways
- Boolean indexing selects elements where True
- np.where(condition, x, y) works like ternary operator
- Use np.logical_and/or for multiple conditions
- These operations return new arrays, not modify originals