Skip to content

A Complete Guide to Comparison Operators in NumPy

Updated: at 05:33 AM

NumPy is a fundamental Python library for scientific computing and data analysis. It provides support for large, multi-dimensional arrays and matrices along with a large library of high-level mathematical functions to operate on these arrays.

Comparison operators in NumPy allow you to compare NumPy arrays element-wise and produce boolean arrays as output. The main comparison operators supported by NumPy are > (greater than), >= (greater than or equal to), < (less than), <= (less than or equal to), == (equal to), != (not equal to). NumPy also provides bitwise comparison operators like & (bitwise AND) and | (bitwise OR) for boolean array operations.

Understanding how to use these comparison operators correctly is essential for evaluating conditional logic and filtering data in NumPy. This comprehensive guide will walk through each of these operators with clear explanations and example code snippets.

Table of Contents

Open Table of Contents

Overview of Key Comparison Operators

Here is a quick overview of the main comparison operators we will cover:

These operators work element-wise on NumPy arrays. We will explore the usage of each through examples.

Importing NumPy

Before using any NumPy functionality, we first need to import the numpy package:

import numpy as np

The numpy package is conventionally imported using np as the alias.

NumPy Array Creation

To illustrate the comparison operators, we need to start by creating NumPy arrays to work with.

There are a few different ways to initialize new NumPy arrays:

# Directly from a list
np_arr = np.array([1, 2, 3])

# Using NumPy functions like arange, zeros, ones etc.
np_arr = np.arange(5)

# Creating empty arrays
np_arr = np.empty(3)

For our examples, let’s create two simple numeric arrays:

arr1 = np.array([1, 2, 3])
arr2 = np.array([3, 2, 1])

Element-wise Comparison

The main feature of NumPy’s comparison operators is that they work element-wise between arrays.

For example:

arr1 > arr2

This compares each element in arr1 with the corresponding element in arr2 and returns a boolean array:

array([False, False, True])

The values [1, 2, 3] are compared to [3, 2, 1] respectively, with results [False, False, True].

Let’s look at more examples of element-wise comparison.

Greater Than (>)

The greater than operator (>) compares each element separately and returns True if the left operand is greater than the right operand:

import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([0, 2, 4])

print(arr1 > arr2)

# Output
[ True False False]

Here 1 > 0 returns True, 2 <= 2 returns False, and 3 < 4 returns False.

Greater Than or Equal To (>=)

The greater than or equal to operator (>=) returns True if the left operand is greater than OR equal to the right operand.

arr1 = np.array([1, 2, 3])
arr2 = np.array([1, 2, 2])

print(arr1 >= arr2)

# Output
[ True  True  True]

Since 1 >= 1, 2 >= 2, and 3 >= 2 are all True, it returns a boolean array [True, True, True].

Less Than (<)

The less than operator (<) evaluates if the left operand is less than the right operand.

arr1 = np.array([1, 4, 3])
arr2 = np.array([2, 2, 2])

print(arr1 < arr2)

# Output:
[ True False False]

Here 1 < 2 is True, 4 < 2 is False, and 3 < 2 is False.

Less Than or Equal To (<=)

This operator (<) returns True if the left operand is less than OR equal to the right operand.

arr1 = np.array([1, 2, 3])
arr2 = np.array([2, 2, 2])

print(arr1 <= arr2)

# Output
[ True  True  True]

Since 1 <= 2, 2 <= 2, and 3 <= 2 evaluate to True, the result is a boolean array [True, True, True].

Equal To (==)

The equal to operator (==) compares each element and returns True if the elements at that index are equal between the two arrays:

arr1 = np.array([1, 2, 3])
arr2 = np.array([1, 2, 3])

print(arr1 == arr2)

# Output
[ True  True  True]

As 1 == 1, 2 == 2, and 3 == 3, it results in [True, True, True].

Not Equal To (!=)

The != operator compares if the array elements at each index are NOT equal.

arr1 = np.array([1, 2, 3])
arr2 = np.array([1, 4, 3])

print(arr1 != arr2)

# Output
[False  True False]

Here 1 == 1 is False, 2 != 4 is True, and 3 == 3 is False.

This covers the main relational operators for element-wise comparison in NumPy. Next, let’s see how we can combine boolean arrays using bitwise operators.

Bitwise Operators

NumPy provides & (bitwise AND) and | (bitwise OR) operators for boolean array operations.

These work at the element level similar to arithmetic operators, applying AND/OR conditions across boolean array elements.

Bitwise AND (&)

The & operator performs a boolean AND operation between corresponding elements:

import numpy as np

arr1 = np.array([True, False, True])
arr2 = np.array([True, True, False])

print(arr1 & arr2)

# Output
[ True False False]

For each position, it returns True only if both elements are True, else False.

Here, True & True = True, False & True = False, True & False = False.

So it results in the boolean array [True, False, False].

Bitwise OR (|)

The | operator performs element-wise boolean OR operation:

arr1 = np.array([True, False, False])
arr2 = np.array([True, True, False])

print(arr1 | arr2)

# Output
[ True  True False]

It returns True if either of the operands is True at that index.

Here, True | True = True, False | True = True, False | False = False, resulting in [True, True, False].

These bitwise operators allow combining boolean arrays in different ways for conditional filtering.

Practical Examples

Now let’s apply these comparison operators to solve some common problems:

Filtering Data

Comparison operators can filter a NumPy array based on conditions:

nums = np.array([1, 2, 3, 4, 5, 6, 7])

# Filter for nums > 3
print(nums[nums > 3])

# Output
[4 5 6 7]

Here we select elements from the nums array where the condition nums > 3 is True.

The same works for other comparisons like >=, <, <= etc. This is a useful technique for filtering arrays based on constraints.

Validating Data

We can validate elements in an array using the == operator:

ages = np.array([18, 21, 16, 17])

# Check if any ages are under 18
print(ages[ages < 18])

# Output
[16]

This verifies that all elements meet a criteria, e.g. being >= 18 years in this case.

Combining Comparisons

Multiple conditions can be combined using boolean operators:

nums = np.array([5, 5, 3, 7, 6])

# Filter where elem > 5 AND < 7
print(nums[(nums > 5) & (nums < 7)])

# Output
[6]

Here & (AND) operator is used to combine two comparisons to filter the array.

We can similarly use | (OR) to combine multiple comparison conditions.

Comparing 2 arrays

We can directly compare two arrays element-wise using comparison operators:

arr1 = np.array([5, 3, 2, 1])
arr2 = np.array([4, 6, 2, 1])

print(arr1 > arr2)

# Output
[ True False False False]

This gives a boolean array result showing where arr1 elements are greater than arr2.

Summary

To recap, the main points about NumPy comparison operators covered in this guide are:

Mastering these simple but powerful operators will allow you to tackle more complex array computations and unlock the full potential of NumPy’s vectorized operations.

I hope you found this guide on comparison operators in NumPy comprehensive and helpful. Let me know if you have any other questions!