🐍 NumPy – Slicing with Boolean Arrays
Boolean slicing in NumPy is a powerful technique used to filter arrays based on conditions.
Instead of using loops, NumPy allows you to apply conditions directly to arrays and extract only the required elements.
This technique is also known as:
- Boolean indexing
- Masking
- Conditional filtering
It is widely used in:
- Data science
- Machine learning
- Data cleaning
- Image processing
- Statistical analysis
What is Boolean Slicing?
Boolean slicing means using a boolean array (True/False values) to select elements from a NumPy array.
True→ element is selectedFalse→ element is ignored
Example Concept
Array: [10, 20, 30, 40, 50]
Condition: > 25
Result: [30, 40, 50]🔵 Creating Boolean Arrays
A boolean array is created by applying a condition.
Example
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print(arr > 25)Output:
[False False True True True]🟢 Using Boolean Array for Filtering
Now use this boolean array to filter values.
result = arr[arr > 25]
print(result)Output:
[30 40 50]🟡 Multiple Conditions (AND)
Use & operator for AND condition.
arr = np.array([10, 15, 20, 25, 30, 35, 40])
result = arr[(arr > 15) & (arr < 40)]
print(result)Output:
[20 25 30 35]🔴 Multiple Conditions (OR)
Use | operator for OR condition.
result = arr[(arr < 15) | (arr > 35)]
print(result)Output:
[10 40]⚠️ Important Rule: Use Parentheses
When combining conditions, always use parentheses.
(arr > 10) & (arr < 40)✔ Correct
❌ arr > 10 & arr < 40 (Wrong)
🟣 Boolean Slicing in 2D Arrays
arr = np.array([
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]
])
print(arr[arr > 50])Output:
[60 70 80 90]🟤 Replace Values Using Boolean Mask
You can also modify data using conditions.
arr = np.array([10, 20, 30, 40, 50])
arr[arr > 30] = 99
print(arr)Output:
[10 20 30 99 99]🔵 Boolean Masking for Data Cleaning
data = np.array([10, -5, 20, -1, 30])
cleaned = data[data > 0]
print(cleaned)Output:
[10 20 30]✔ Removes invalid or negative values
🧠 How Boolean Indexing Works
Step-by-step process:
- Apply condition on array
- NumPy creates boolean mask
- Mask is applied to filter data
- Only True values are returned
📊 Boolean Slicing vs Fancy Indexing
| Feature | Boolean Slicing | Fancy Indexing |
|---|---|---|
| Based on | Condition | Index list |
| Selection | Dynamic | Manual |
| Flexibility | High | High |
| Use case | Filtering | Specific selection |
⚡ Real-World Example
Filtering student marks
marks = np.array([45, 67, 89, 30, 55, 90])
passed = marks[marks >= 50]
print(passed)Output:
[67 89 55 90]🖼️ Image Processing Example
image = np.array([
[100, 150, 200],
[50, 80, 120],
[30, 60, 90]
])
bright = image[image > 100]
print(bright)Output:
[150 200 120]✔ Used in computer vision for pixel filtering
🚀 Performance Tips
- Boolean slicing is vectorized (very fast)
- Avoid loops when filtering data
- Use
.copy()if you need independent data - Combine conditions carefully for efficiency
⚠️ Common Errors
1. Missing parentheses
ValueError or unexpected result✔ Fix:
(arr > 10) & (arr < 20)2. Using Python keywords instead of operators
❌ and, or
✔ Use &, |
🧾 Summary
NumPy boolean slicing allows you to:
- Filter arrays using conditions
- Apply logical operations
- Clean and transform data
- Modify values efficiently
🏁 Conclusion
Boolean slicing is one of the most powerful features in NumPy. It enables fast, readable, and efficient data filtering without loops.
It is essential for:
- Data science
- Machine learning
- Data preprocessing
- Image processing


0 Comments