0
0
NumPydata~5 mins

Comparison operations in NumPy

Choose your learning style9 modes available
Introduction

Comparison operations help us check if values are equal, bigger, or smaller. This is useful to find patterns or filter data.

Checking which students scored above a passing grade in a test.
Finding products that cost less than a certain price in a store.
Selecting days when the temperature was higher than average.
Filtering emails that arrived before a specific date.
Syntax
NumPy
array1 == array2
array1 != array2
array1 > array2
array1 >= array2
array1 < array2
array1 <= array2

These operations compare elements of arrays element-wise.

They return a new array of True/False values showing the comparison result.

Examples
Checks which elements are greater than 2.
NumPy
import numpy as np

arr = np.array([1, 2, 3, 4])
print(arr > 2)
Checks element-wise equality between two arrays.
NumPy
arr1 = np.array([1, 2, 3])
arr2 = np.array([3, 2, 1])
print(arr1 == arr2)
Checks which elements are less than or equal to 10.
NumPy
arr = np.array([5, 10, 15])
print(arr <= 10)
Sample Program

This program checks which scores are greater than or equal to 60. It prints the original scores, a True/False array showing who passed, and then only the passing scores.

NumPy
import numpy as np

scores = np.array([55, 70, 85, 40, 90])
passing_score = 60
passed = scores >= passing_score
print("Scores:", scores)
print("Passed:", passed)

# Filter scores that passed
passed_scores = scores[passed]
print("Scores that passed:", passed_scores)
OutputSuccess
Important Notes

Comparison results can be used to filter or select data easily.

All arrays compared must have the same shape or be broadcastable.

Summary

Comparison operations compare arrays element-wise and return True/False arrays.

They help find or filter data based on conditions.

Common operators: ==, !=, >, >=, <, <=.