NumPy Array Comparisons
In NumPy, you can compare arrays just like numbers.
Instead of checking values one by one using loops, NumPy allows element-wise comparisons directly on arrays.
This is called Element-wise Array Comparison.
What are Element-wise Comparisons in NumPy?
Element-wise comparison means:
Comparing each element of an array with another value or array individually.
The result is always a Boolean array (True/False).
Why Use Array Comparisons?
- Fast and efficient filtering
- No need for loops
- Used in data cleaning
- Essential for machine learning
- Helps in conditional selection
1. Basic Comparison Example
import numpy as np
arr = np.array([10, 20, 30, 40])
result = arr > 25
print(result)
Output:
[False False True True]
2. Equal Comparison
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr == 3)
Output:
[False False True False]
3. Not Equal Comparison
arr = np.array([5, 10, 15, 20])
print(arr != 10)
Output:
[ True False True True]
4. Greater Than / Less Than
arr = np.array([5, 15, 25, 35])
print(arr < 20)
print(arr >= 25)
Output:
[ True True False False]
[False False True True]
5. Comparing Two Arrays
import numpy as np
a = np.array([1, 2, 3])
b = np.array([3, 2, 1])
print(a > b)
Output:
[False False True]
How Element-wise Comparison Works
a = [1, 2, 3]
b = [3, 2, 1]
Result = [1>3, 2>2, 3>1]
= [False, False, True]
Boolean Array Filtering
You can use comparisons to filter data:
arr = np.array([10, 20, 30, 40, 50])
filtered = arr[arr > 25]
print(filtered)
Output:
[30 40 50]
Multiple Conditions
arr = np.array([10, 20, 30, 40, 50])
result = (arr > 20) & (arr < 50)
print(result)
Output:
[False False True True False]
Logical Operators in NumPy
| Operator | Meaning |
|---|---|
| & | AND |
| | | OR |
| ~ | NOT |
Real-World Use Cases
Element-wise comparisons are used in:
- Data filtering
- Machine learning preprocessing
- Image thresholding
- Statistical analysis
- Database-like queries
Example: Filtering Students Marks
marks = np.array([45, 60, 75, 30, 90])
passed = marks[marks >= 50]
print(passed)
Output:
[60 75 90]
Example: Image Thresholding
binary_image = image > 128
✔ Converts image to black & white mask
Comparison vs Python Lists
❌ Python List:
[1, 2, 3] > 2
❌ Not supported
✅ NumPy Array:
np.array([1,2,3]) > 2
✔ Works perfectly
Advantages of Array Comparisons
- Fast execution
- No loops needed
- Easy filtering
- Works with large datasets
- Essential for data science
Summary
NumPy element-wise array comparisons allow you to compare arrays efficiently and generate boolean results for filtering and analysis.
This feature is widely used in NumPy and is essential for data processing in Python.
Conclusion
Mastering element-wise comparisons helps you filter, analyze, and manipulate data efficiently in Python, making your code faster and more powerful.


0 Comments