Master NumPy From Scratch

Learn NumPy fundamentals, arrays, indexing, slicing, data types, array operations, broadcasting, mathematical functions, statistics, random numbers, linear algebra, file handling, and practical projects through structured lessons.

COURSE SYLLABUS
1. NumPy Introduction and Installation
Introduction to NumPy NumPy Installation and Setup NumPy Environment and IDE Setup First NumPy Program
2. NumPy Arrays and Array Creation
NumPy Array Fundamentals Array Creation Functions Zeros, Ones and Identity Arrays Range and Linspace Arrays
3. NumPy Array Indexing and Slicing
One-Dimensional Array Indexing Array Slicing Techniques Two-Dimensional Array Indexing Boolean and Fancy Indexing
4. NumPy Data Types and Attributes
NumPy Data Types Array Shape, Size and Dimensions Data Type Conversion and Casting Array Inspection and Attributes
5. NumPy Array Shape and Reshaping
Reshape and Flatten Arrays Transpose and Axis Operations Stacking and Splitting Arrays Expand and Squeeze Dimensions
6. NumPy Array Operations and Broadcasting
Arithmetic Array Operations Comparison and Logical Operations Broadcasting Fundamentals Universal Functions and Vectorization
7. NumPy Mathematical and Statistical Functions
Mathematical Functions Aggregate and Statistical Functions Minimum, Maximum and Percentiles Rounding and Trigonometric Functions
8. NumPy Filtering and Sorting
Array Filtering and Conditions Sorting and Searching Arrays Unique Values and Set Operations Where, Select and Nonzero Functions
9. NumPy Copies and Views
Array Copies and Views Shallow and Deep Copy Concepts Memory Layout and Contiguity Array Iteration and Memory Efficiency
10. NumPy Random Number Generation
Random Generator Fundamentals Random Integers and Sampling Probability Distributions Random Seeds and Simulation
11. NumPy Linear Algebra
Vectors and Matrices Matrix Multiplication and Dot Product Determinants and Matrix Inverse Eigenvalues and Linear Equations
12. NumPy File Input and Output
Importing and Exporting Text Files CSV Data with NumPy Binary Files and NPY Format NPZ Files and Data Persistence
13. NumPy Practical Projects
Student Marks Analysis Project Sales Data Analysis Project Random Simulation Project Image Array Processing Project
14. NumPy Practice and Assessment
NumPy Beginner Practice NumPy Intermediate Exercises NumPy Advanced Challenges Final NumPy Assessment

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.

import numpy as np marks = np.array([45, 72, 30, 88, 55]) result = marks >= 40 print(result)

Output:

[ True True False True True]

NumPy compares each mark with 40. Values greater than or equal to 40 produce True, while the value 30 produces False.

Comparison: marks >= 40 Marks Result 45 72 30 88 55 True True False True True Only the value 30 fails the comparison.

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

import numpy as np values = np.array([10, 20, 30, 40, 50]) print("Equal to 30:", values == 30) print("Not equal to 30:", values != 30) print("Greater than 30:", values > 30) print("Less than 30:", values < 30) print("At least 30:", values >= 30) print("At most 30:", values <= 30)

Output:

Equal to 30: [False False True False False] Not equal to 30: [ True True False True True] Greater than 30: [False False False True True] Less than 30: [ True True False False False] At least 30: [False False True True True] At most 30: [ True True True False False]
Tip: Use >= 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.

import numpy as np previous = np.array([60, 75, 80, 55]) current = np.array([65, 70, 90, 55]) improved = current > previous print(improved)

Output:

[ True False True False]

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

import numpy as np first = np.array([10, 20, 30, 40]) second = np.array([10, 25, 30, 35]) same = first == second print(same) print("Equal positions:", np.where(same))

Output:

[ True False True False] Equal positions: (array([0, 2]),)

The values are equal at indices 0 and 2. NumPy's np.where() can identify the positions where a Boolean condition is true.

Important: Arrays with different shapes may still be comparable when their shapes are compatible under broadcasting rules. Incompatible shapes raise a 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.
import numpy as np a = np.array([5, 10, 15, 20]) b = np.array([5, 8, 15, 25]) print(np.equal(a, b)) print(np.greater(a, b)) print(np.less(a, b)) print(np.not_equal(a, b))

Output:

[ True False True False] [False True False False] [False False False True] [False True False True]

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.

import numpy as np marks = np.array([85, 72, 90, 65, 78]) attendance = np.array([90, 85, 75, 95, 88]) eligible = np.logical_and( marks >= 75, attendance >= 80 ) print(eligible)

Output:

[ True False False False True]

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.

import numpy as np values = np.array([10, 20, 30, 40, 50]) condition = (values >= 20) & (values <= 40) print(condition) print(values[condition])

Output:

[False True True True False] [20 30 40]
Remember: Use & 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.

21141512
import numpy as np marks = np.array([35, 65, 80, 45, 90]) condition = np.logical_or( marks < 40, marks >= 80 ) print(condition) print(marks[condition])

Output:

[ True False True False True] [35 80 90]

This condition selects values below 40 or at least 80. A value is selected when either comparison is true.

Using the | Operator

import numpy as np temperatures = np.array([18, 24, 31, 36, 22, 40]) condition = (temperatures < 20) | (temperatures > 35) print(temperatures[condition])

Output:

[18 36 40]

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.

import numpy as np values = np.array([10, 20, 30, 40, 50]) greater_than_25 = values > 25 not_greater_than_25 = np.logical_not(greater_than_25) print("Original condition:", greater_than_25) print("Inverted condition:", not_greater_than_25) print("Selected values:", values[not_greater_than_25])

Output:

Original condition: [False False True True True] Inverted condition: [ True True False False False] Selected values: [10 20]

The inverted condition selects the values that are not greater than 25. In this example, those values are 10 and 20.

Important: When using ~, 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.

import numpy as np condition_a = np.array([True, True, False, False]) condition_b = np.array([True, False, True, False]) result = np.logical_xor(condition_a, condition_b) print(result)

Output:

[False True True False]
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.

import numpy as np marks = np.array([45, 82, 67, 91, 73, 58, 88]) condition = (marks >= 70) & (marks <= 90) selected_marks = marks[condition] print("All marks:", marks) print("Condition:", condition) print("Selected marks:", selected_marks)

Output:

All marks: [45 82 67 91 73 58 88] Condition: [False True False False True False True] Selected marks: [82 73 88]

The filter includes marks from 70 through 90, including both boundaries. Values below 70 and above 90 are excluded.

Combining Three Conditions

import numpy as np marks = np.array([85, 72, 95, 68, 78, 91]) attendance = np.array([90, 88, 75, 95, 82, 92]) assignments = np.array([8, 9, 10, 7, 8, 9]) condition = ( (marks >= 75) & (attendance >= 80) & (assignments >= 8) ) print(marks[condition])

Output:

[85 78 91]

All three conditions must be true for a record to be selected. This pattern is useful when multiple eligibility rules must be satisfied simultaneously.

Best practice: Use parentheses around every comparison when combining conditions with & 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)
import numpy as np values = np.array([5, 15, 25, 35]) # Correct: element-wise logical combination condition = (values >= 10) & (values <= 30) print(values[condition])

Output:

[15 25]
Common mistake: Do not write (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:

  1. Create arrays for student marks and attendance percentages.
  2. Find students whose marks are at least 75.
  3. Find students whose attendance is at least 80.
  4. Use logical AND to identify students who satisfy both requirements.
  5. Use logical OR to identify students who satisfy at least one requirement.
  6. Use logical XOR to identify students who satisfy exactly one requirement.
  7. Display the selected marks and the Boolean conditions.

Sample Solution

import numpy as np marks = np.array([85, 68, 92, 74, 79, 60]) attendance = np.array([90, 95, 75, 82, 88, 70]) marks_condition = marks >= 75 attendance_condition = attendance >= 80 both_conditions = np.logical_and( marks_condition, attendance_condition ) either_condition = np.logical_or( marks_condition, attendance_condition ) exactly_one = np.logical_xor( marks_condition, attendance_condition ) print("Marks condition:", marks_condition) print("Attendance condition:", attendance_condition) print("Both requirements:") print(marks[both_conditions]) print("At least one requirement:") print(marks[either_condition]) print("Exactly one requirement:") print(marks[exactly_one])

Expected output:

Marks condition: [ True False True False True False] Attendance condition: [ True True False True True False] Both requirements: [85 79] At least one requirement: [85 68 92 74 79] Exactly one requirement: [68 92 74]

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.

import numpy as np a = np.array([0.1 + 0.2, 0.5]) b = np.array([0.3, 0.5]) print(a == b) print(np.isclose(a, b))

Typical output:

[False True] [ True True]

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.