# 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.

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

**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.

**It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.**

https://www.w3resource.com/python-exercises/numpy/basic/numpy-basic-exercise-53.php

**Weekly Trends and Language Statistics**- Weekly Trends and Language Statistics