w3resource

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

NumPy: Basic Exercise-53 with Solution

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

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]) 

Sample 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:

Previous: NumPy program to sort a given array by row and column in ascending order.
Next: NumPy program to replace all numbers in a given array which is equal, less and greater to a given number.

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.