w3resource

NumPy: Create an element-wise comparison (greater, greater_equal, less and less_equal) of two given arrays

NumPy: Basic Exercise-10 with Solution

Write a NumPy program to create an element-wise comparison (greater, greater_equal, less and less_equal) of two given arrays.

Sample Solution :

Python Code :

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating NumPy arrays 'x' and 'y' containing numbers for comparison
x = np.array([3, 5])
y = np.array([2, 5])

# Printing the original numbers stored in arrays 'x' and 'y'
print("Original numbers:")
print(x)
print(y)

# Performing element-wise comparison (greater than) between arrays 'x' and 'y', and printing the result
print("Comparison - greater")
print(np.greater(x, y))

# Performing element-wise comparison (greater than or equal to) between arrays 'x' and 'y', and printing the result
print("Comparison - greater_equal")
print(np.greater_equal(x, y))

# Performing element-wise comparison (less than) between arrays 'x' and 'y', and printing the result
print("Comparison - less")
print(np.less(x, y))

# Performing element-wise comparison (less than or equal to) between arrays 'x' and 'y', and printing the result
print("Comparison - less_equal")
print(np.less_equal(x, y)) 

Sample Output:

Original numbers:
[3 5]
[2 5]
Comparison - greater
[ True False]
Comparison - greater_equal
[ True  True]
Comparison - less
[False False]
Comparison - less_equal
[False  True]                         

Explanation:

At first we declare two arrays x = np.array([3, 5]) and y = np.array([2, 5])
print(np.greater(x, y)): Here np.greater() function compares the elements of 'x' and 'y' element-wise and check if the corresponding elements of 'x' are greater than those of 'y'. The function returns a boolean array [True, False].

print(np.greater_equal(x, y)): Here the np.greater_equal() function compares the elements of 'x' and 'y' element-wise and check if the corresponding elements of 'x' are greater than or equal to those of 'y'. The function returns a boolean array [True, True].

print(np.less(x, y)): Here the np.less() function compares the elements of 'x' and 'y' element-wise and check if the corresponding elements of 'x' are less than those of 'y'. The function returns a boolean array [False, False].

print(np.less_equal(x, y)): Here np.less_equal() function compares the elements of 'x' and 'y' element-wise and check if the corresponding elements of 'x' are less than or equal to those of 'y'. The function returns a boolean array [False, True].

Python-Numpy Code Editor:

Previous: Test if two arrays are element-wise equal within a tolerance.
Next: Create an element-wise comparison (equal, equal within a tolerance) of two given arrays.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.