Boolean Indexing & Filtering in NumPy (Advanced Data Selection)

πŸ“Œ Introduction

When working with datasets, you often need to filter specific values.

That’s where Boolean Indexing in NumPy becomes extremely powerful.


πŸ” What is Boolean Indexing?

Boolean indexing allows you to:

  • Filter data based on conditions
  • Extract only required values
  • Perform dynamic queries

πŸ§ͺ Example Array

import numpy as nparr = np.array([10, 20, 30, 40, 50])

βœ… 1. Basic Boolean Condition

print(arr > 25)

πŸ‘‰ Output:

[False False  True  True  True]

βœ” Returns True/False for each element


πŸ”Ž 2. Filtering Values

print(arr[arr > 25])

πŸ‘‰ Output:

[30 40 50]

βœ” Only values satisfying condition are returned


πŸ”— 3. Multiple Conditions

print(arr[(arr > 20) & (arr < 50)])

πŸ‘‰ Output:

[30 40]

βœ” Operators:

  • & β†’ AND
  • | β†’ OR

πŸ“Š 4. Boolean Indexing in 2D Arrays

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

πŸ‘‰ Output:

[4 5 6]

πŸ”„ 5. Modify Values Using Condition

arr = np.array([10, 20, 30, 40])arr[arr > 25] = 0
print(arr)

πŸ‘‰ Output:

[10 20  0  0]

βœ” Replace values dynamically


⚑ Why Boolean Indexing is Powerful?

Using NumPy, you can:

  • Avoid loops
  • Filter large datasets instantly
  • Write clean & efficient code

πŸ“¦ Real-World Use Cases

Boolean indexing is widely used in:

  • Data cleaning
  • Filtering datasets
  • Machine learning preprocessing

πŸ”— Used with Other Libraries

Works seamlessly with:

  • Pandas
  • Scikit-learn
  • TensorFlow

πŸ“Š Summary Table

OperationExample
Conditionarr > 25
Filterarr[arr > 25]
AND(arr > 20) & (arr < 50)
Modifyarr[arr > 25] = 0

🧠 Pro Tips

  • Always use parentheses in multiple conditions
  • Use boolean indexing instead of loops
  • Combine with slicing for advanced queries

πŸ”š Conclusion

Boolean indexing in NumPy is a must-know skill for efficient data filtering and manipulation.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *