w3resource

NumPy: Numbers from a given array which are less and greater than a specified number


Extract Numbers Less/Greater Than Value

Write a NumPy program to extract all numbers from a given array less and greater than a specified number.

This problem involves writing a NumPy program to extract all numbers from a given array that are both less than or greater than a specified number. The task requires utilizing NumPy's array manipulation capabilities, such as boolean indexing, to efficiently filter out the elements based on the specified condition. By applying conditional selection techniques, the program extracts the desired subset of numbers from the array, providing flexibility in data extraction for various analytical tasks.

Sample Solution:

Python Code :

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

# Creating a NumPy array 'nums' containing values in a 3x3 matrix
nums = np.array([[5.54, 3.38, 7.99],
              [3.54, 4.38, 6.99],
              [1.54, 2.39, 9.29]])

# Printing a message indicating the original array
print("Original array:")
print(nums)

# Assigning value 5 to the variable 'n' and printing elements greater than 'n' in the array
n = 5
print("\nElements of the said array greater than", n)
print(nums[nums > n])

# Assigning value 6 to the variable 'n' and printing elements less than 'n' in the array
n = 6
print("\nElements of the said array less than", n)
print(nums[nums < n]) 

Output:

Original array:
[[5.54 3.38 7.99]
 [3.54 4.38 6.99]
 [1.54 2.39 9.29]]

Elements of the said array greater than 5
[5.54 7.99 6.99 9.29]

Elements of the said array less than 6
[5.54 3.38 3.54 4.38 1.54 2.39]

Explanation:

In the above code:

nums = np.array(...): Creates a 3x3 NumPy array with the given values.

n = 5: Set the variable n to 5.

print(nums[nums > n]): This line uses boolean indexing to filter out elements in the nums array that are greater than n (5). The result is a 1D NumPy array containing the filtered elements and the results are printed.

n = 6: Set the variable n to 6.

print(nums[nums < n]): This line uses boolean indexing to filter out elements in the nums array that are less than n (6). The result is a 1D NumPy array containing the filtered elements and the results are printed.

Python-Numpy Code Editor: