NumPy – Using less() and less_equal() functions (5 examples)

Updated: February 26, 2024 By: Guest Contributor Post a comment

Introduction

NumPy, a cornerstone library in Python for scientific computing, furnishes a vast array of functions to operate on arrays. Among its versatile suite, less() and less_equal() functions are pivotal in element-wise comparison across arrays. This article delves into comprehensively unraveling the prowess of these functions through a series of five progressively complex examples. From the basics of syntax to advanced applications, this tutorial aims to elevate your data analysis skills.

Basic Example: Understanding less()

Let’s embark on our journey with a fundamental demonstration of the less() function. This function compares two arrays element-wise and returns a new array with boolean values, indicating whether each element in the first array is less than the corresponding element in the second array.

import numpy as np

a = np.array([1, 2, 3])
b = np.array([3, 2, 1])
result = np.less(a, b)

print(result)

Output:

[ True, False, False]

This simple example illustrates the elemental efficacy of less() in comparing numeric array elements.

Exploring less_equal()

Moving a notch higher, the less_equal() function works similarly by comparing two arrays element-wise. However, it incorporates equality in its operation – it checks if elements in the first array are less than or equal to their counterparts in the second array, returning a boolean array.

import numpy as np

a = np.array([3, 3, 3])
b = np.array([3, 2, 4])
result = np.less_equal(a, b)

print(result)

Output:

[ True, False, True]

This example underlines the nuanced difference between less() and less_equal(), offering versatility in comparisons.

Conditional Filtering with less() and less_equal()

Deeper into practical applications, these comparison functions are not just limited to comparing arrays; they greatly facilitate conditional filtering within arrays. This entails leveraging the boolean arrays returned by less() and less_equal() as masks to filter data.

import numpy as np

prices = np.array([20, 30, 15, 25])
threshold = 25

cheap_prices_mask = np.less(prices, threshold)
cheap_prices = prices[cheap_prices_mask]

print("Cheap prices:", cheap_prices)

Output:

Cheap prices: [20 15]

This method is invaluable in data science, where such conditional filtering forms the crux of data manipulation and cleaning.

Advanced Multidimensional Arrays Comparison

Scaling the complexity, we now explore how less() and less_equal() operate on multidimensional arrays. The element-wise comparison extends seamlessly to higher dimensions, providing crucial insights into array-based datasets.

import numpy as np

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

# Using less()
result_less = np.less(arr1, arr2)
# Using less_equal()
result_less_equal = np.less_equal(arr1, arr2)

print("Using less():")
print(result_less)
print("\nUsing less_equal():")
print(result_less_equal)

Output:

Using less():
[[ True,  True,  True]
 [False, False, False]]

Using less_equal():
[[ True,  True,  True]
 [False, False,  True]]

These examples illustrate how comparisons extend beyond single-dimensional arrays, applying also to matrices and potentially tensors, unlocking analysis in n-dimensional space.

Integrating less() and less_equal() in Data Analysis

Here’s a NumPy example that demonstrates the use of np.less() and np.less_equal() functions in the context of a data analysis project, such as screening temperature data across different cities to identify anomalies or extremes:

import numpy as np

# Sample temperature data (in degrees Celsius) for different cities
temperatures = np.array([22, 30, 15, 28, 31, 10, 25, 27])
# Threshold for identifying high temperature anomalies
high_temp_threshold = 30
# Threshold for identifying low temperature extremes
low_temp_threshold = 12

# Use np.less() to identify temperatures below the low temperature threshold
low_temps = np.less(temperatures, low_temp_threshold)

# Use np.less_equal() to identify temperatures that are equal to or exceed the high temperature threshold
high_temps = np.less_equal(high_temp_threshold, temperatures)

# Indices of cities with temperature anomalies or extremes
low_temp_indices = np.where(low_temps)[0]
high_temp_indices = np.where(high_temps)[0]

print(f"Temperatures: {temperatures}")
print(f"Low temperature extremes (below {low_temp_threshold}C): {temperatures[low_temp_indices]}")
print(f"High temperature anomalies (above or equal to {high_temp_threshold}C): {temperatures[high_temp_indices]}")

# Assuming city names corresponding to the temperature data
city_names = np.array(['City A', 'City B', 'City C', 'City D', 'City E', 'City F', 'City G', 'City H'])
print(f"Cities with low temperature extremes: {city_names[low_temp_indices]}")
print(f"Cities with high temperature anomalies: {city_names[high_temp_indices]}")

This example creates a NumPy array containing sample temperature data for different cities. It then uses np.less() to identify cities with temperatures below a certain low threshold, indicating potential low temperature extremes, and np.less_equal() to find cities with temperatures that are equal to or exceed a high threshold, indicating potential high temperature anomalies. Finally, it prints the temperatures and corresponding city names that meet these criteria, showcasing how these functions can be integrated into data analysis workflows to screen arrays for relevant insights.

Conclusion

In sum, NumPy’s less() and less_equal() functions are instrumental for performing element-wise comparisons across arrays, facilitating everything from simple data filtering to complex multidimensional data analysis. Through the illustrated examples ranging from basic to advanced applications, it’s evident these functions are not only versatile but also fundamentally essential for data scientists and analysts alike.