Comparison and Logical Operations
Learn how to compare NumPy array elements using comparison operators and combine conditions using logical operations. Explore greater than, less than, equality, inequality, logical AND, logical OR, logical NOT, and conditional filtering through detailed examples and practical numerical datasets.
1. Learning Objectives
By the end of this lesson, you will be able to:
- Understand element-wise comparison operations.
- Use greater than, less than, and equality operators.
- Compare two arrays and compare arrays with scalar values.
- Use
np.equal(),np.greater(), and related functions. - Combine conditions with logical AND and logical OR.
- Invert Boolean conditions using logical NOT.
- Filter array values using multiple conditions.
- Understand the difference between Python logical operators and NumPy logical functions.
2. Introduction to Comparison Operations
Comparison operations evaluate relationships between values.
In NumPy, comparisons are generally performed element by element.
Each comparison produces a Boolean result: True
when the condition is satisfied and False otherwise.
For example, suppose an array stores marks obtained by students. We can compare every mark with a passing threshold to identify which values meet the requirement.
Output:
NumPy compares each mark with 40. Values greater than or equal
to 40 produce True, while the value 30 produces
False.
A comparison creates a Boolean array that can be used for filtering.
3. Comparison Operators in NumPy
NumPy supports the standard Python comparison operators. When applied to arrays, these operators compare corresponding elements and return a Boolean array.
| Operator | Meaning | Example |
|---|---|---|
== |
Equal to | values == 10 |
!= |
Not equal to | values != 10 |
> |
Greater than | values > 10 |
< |
Less than | values < 10 |
>= |
Greater than or equal to | values >= 10 |
<= |
Less than or equal to | values <= 10 |
Example: Applying Different Comparisons
Output:
>= when the boundary
value should also satisfy the condition. For example,
marks >= 40 includes marks equal to 40.
4. Comparing Two NumPy Arrays
You can compare two arrays of compatible shapes. NumPy evaluates each pair of corresponding values and returns a Boolean array. This is useful when comparing previous and current measurements, actual and target sales, or two sets of student marks.
Output:
The first and third values improved. The second value decreased, while the fourth value remained unchanged. The comparison reports whether each current value is greater than its corresponding previous value.
Finding Equal Values
Output:
The values are equal at indices 0 and 2. NumPy's
np.where() can identify the positions where
a Boolean condition is true.
ValueError.
5. NumPy Comparison Functions
In addition to comparison operators, NumPy provides named functions for common comparisons. These functions make the purpose of an operation explicit in code.
| Function | Purpose |
|---|---|
np.equal(a, b) |
Checks whether corresponding values are equal. |
np.not_equal(a, b) |
Checks whether corresponding values are different. |
np.greater(a, b) |
Checks whether values in a are greater than values in b. |
np.greater_equal(a, b) |
Checks whether values in a are greater than or equal to values in b. |
np.less(a, b) |
Checks whether values in a are less than values in b. |
np.less_equal(a, b) |
Checks whether values in a are less than or equal to values in b. |
Output:
The named functions produce the same kinds of element-wise Boolean results as their corresponding operators.
6. Introduction to Logical Operations
Logical operations combine or invert Boolean conditions. They are especially useful when a dataset must satisfy more than one requirement.
For example, a student may qualify for a distinction only when marks are at least 75 and attendance is at least 80 percent. NumPy can evaluate both requirements across arrays.
| Logical Operation | NumPy Function | Purpose |
|---|---|---|
| AND | np.logical_and() |
True when both conditions are true. |
| OR | np.logical_or() |
True when at least one condition is true. |
| NOT | np.logical_not() |
Reverses each Boolean value. |
| XOR | np.logical_xor() |
True when the two conditions differ. |
7. Logical AND Operation
Logical AND returns True only when both conditions
are true. NumPy's np.logical_and() evaluates the
logical AND operation element by element.
Output:
A value is true only when the corresponding student has marks of at least 75 and attendance of at least 80. Students who satisfy only one requirement are not selected.
Using the & Operator
The & operator can combine Boolean arrays.
Parentheses should be placed around each comparison to ensure
the expressions are evaluated as intended.
Output:
& for
element-wise logical AND on Boolean arrays. Do not replace it
with Python's and when combining whole NumPy
Boolean arrays.
8. Logical OR Operation
Logical OR returns True when at least one of the
conditions is true. It is useful when a value can qualify through
more than one rule.
Output:
This condition selects values below 40 or at least 80. A value is selected when either comparison is true.
Using the | Operator
Output:
The expression selects temperatures below 20 or above 35. Values between these limits are not selected.
9. Logical NOT Operation
Logical NOT reverses a Boolean condition. True values become
false, and false values become true. NumPy provides
np.logical_not(), while the ~
operator can invert Boolean arrays.
Output:
The inverted condition selects the values that are not greater than 25. In this example, those values are 10 and 20.
~, make sure
you are inverting a Boolean condition. Applying bitwise inversion
directly to an integer array has different behavior.
10. Logical XOR Operation
Exclusive OR, or XOR, returns true when exactly one of the two conditions is true. It returns false when both conditions are true or both are false.
Output:
| Condition A | Condition B | AND | OR | XOR |
|---|---|---|---|---|
| True | True | True | True | False |
| True | False | False | True | True |
| False | True | False | True | True |
| False | False | False | False | False |
11. Filtering Arrays with Multiple Conditions
A Boolean array can be used as a mask to select matching elements from another array. Combining comparison and logical operations allows you to filter data using several conditions at once.
Output:
The filter includes marks from 70 through 90, including both boundaries. Values below 70 and above 90 are excluded.
Combining Three Conditions
Output:
All three conditions must be true for a record to be selected. This pattern is useful when multiple eligibility rules must be satisfied simultaneously.
&
or |. This keeps the intended evaluation order clear.
12. Python Logical Operators vs NumPy Logical Operations
Python's and and or operators work
with scalar truth values. NumPy arrays can contain many Boolean
values, so element-wise logical functions or operators are
normally used to combine array conditions.
| Purpose | Recommended NumPy Approach | Example |
|---|---|---|
| Element-wise AND | & or np.logical_and() |
(a > 0) & (a < 10) |
| Element-wise OR | | or np.logical_or() |
(a < 0) | (a > 10) |
| Invert a Boolean condition | ~ or np.logical_not() |
~(a > 10) |
| Element-wise XOR | np.logical_xor() |
np.logical_xor(a, b) |
Output:
(values >= 10) and (values <= 30) for
NumPy Boolean arrays. Python's and attempts to
evaluate the truth value of an entire array and generally raises
an ambiguous truth-value error when multiple elements are present.
13. Practical Activity
Activity: Student Eligibility Analysis
Samadhan, Pradnya, and Samiksha are analyzing student performance at CIIT TRANING INSTITUTE. A student qualifies for a special recognition list when marks are at least 75 and attendance is at least 80 percent. The team also wants to identify students who satisfy either one of the two requirements but not both.
Tasks:
- Create arrays for student marks and attendance percentages.
- Find students whose marks are at least 75.
- Find students whose attendance is at least 80.
- Use logical AND to identify students who satisfy both requirements.
- Use logical OR to identify students who satisfy at least one requirement.
- Use logical XOR to identify students who satisfy exactly one requirement.
- Display the selected marks and the Boolean conditions.
Sample Solution
Expected output:
The Boolean masks identify which records satisfy each requirement. The final filtered arrays contain the marks for the selected students.
14. Common Mistakes and Best Practices
| Common Mistake | Correct Approach |
|---|---|
Using Python and with entire Boolean arrays. |
Use & or np.logical_and(). |
| Combining comparisons without parentheses. | Write each comparison inside parentheses before using & or |. |
Confusing & with a scalar logical operator. |
Use it for element-wise Boolean conditions in NumPy. |
| Assuming a comparison returns a single Boolean value. | Array comparisons normally return Boolean arrays. |
| Comparing arrays with incompatible shapes. | Check shapes and broadcasting compatibility. |
| Using equality to compare floating-point calculations without considering precision. | For approximate numeric comparisons, consider np.isclose() or np.allclose(). |
Comparing Floating-Point Values
Floating-point calculations may contain small representation
differences. When you need to check whether calculated decimal
values are approximately equal, use np.isclose()
instead of relying only on exact equality.
Typical output:
The first exact comparison can be false because floating-point
values may not represent decimal fractions exactly. The
np.isclose() function checks approximate equality
within configured tolerances.
Summary
In this lesson, we learned how to compare NumPy arrays using equality, inequality, greater-than, less-than, and related comparison operators. We explored NumPy comparison functions and learned that array comparisons produce Boolean arrays containing True and False values.
We also studied logical AND, OR, NOT, and XOR operations and used them to combine multiple conditions. Boolean masks allow us to filter arrays based on eligibility rules, numerical ranges, and other requirements. Remember to use parentheses around comparisons, use element-wise logical operators for arrays, and check shape compatibility. For floating-point calculations, consider approximate comparison functions when exact equality is not appropriate.