Boolean indexing (masking) allows you to select elements of an array based on conditions. np.where(condition, x, y) returns elements chosen from x or y depending on condition.
NumPy Boolean Masking and Where
Filter and replace array values conditionally using np.where.
Key Takeaways: NumPy Boolean Masking and Where
Mastering NumPy Boolean Masking and Where helps you write clean and reliable NumPy code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
NumPy Boolean Masking and Where Code Example
NumPyimport numpy as np
arr = np.array([15, 25, 35, 45, 55])
# Replace values > 30 with 99, otherwise keep original
result = np.where(arr > 30, 99, arr)
print("Conditionally replaced:", result)
Output
Conditionally replaced: [15 25 99 99 99]
Free sign-in required · Google login available
Finished this lesson?
Mark it complete to track your progress.
Stuck on something?
Ask the community in the CodesInTech forum.
Need a developer?
Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.
Explore Our Services