w3resource

NumPy: Find elements within range from a given array of numbers

NumPy: Array Object Exercise-149 with Solution

Write a NumPy program to find elements within a range from a given array of numbers.

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating a NumPy array 'a' containing integers
a = np.array([1, 3, 7, 9, 10, 13, 14, 17, 29])

# Displaying a message indicating the original array will be printed
print("Original array:")

# Printing the original array 'a'
print(a)

# Using NumPy's logical_and function to find indices where elements are within the range [7, 20]
result = np.where(np.logical_and(a >= 7, a <= 20))

# Displaying a message indicating the elements within the specified range along with their index positions
print("\nElements within range: index position")

# Printing the index positions of elements that satisfy the condition
print(result) 

Sample Output:

Original array:
[ 1  3  7  9 10 13 14 17 29]

Elements within range: index position
(array([2, 3, 4, 5, 6, 7]),)

Explanation:

a = np.array([1, 3, 7, 9, 10, 13, 14, 17, 29]): It creates a 1-dimensional NumPy array a with the given elements.

np.logical_and(a>=7, a<=20): This line of code creates a boolean array of the same shape as a. It applies two element-wise conditions, checking whether each element in a is greater than or equal to 7 and less than or equal to 20. The result is a boolean array where each element is True if both conditions are met and False otherwise.

result = np.where(np.logical_and(a>=7, a<=20)): np.where is used to find the indices of the elements in the array where the corresponding boolean value in the input array is True. In this case, it finds the indices of elements in a that satisfy the given condition (between 7 and 20, inclusive).

print(result): It prints the resulting indices as a ‘tuple’.

Pictorial Presentation:

NumPy: Find elements within range from a given array of numbers

Python-Numpy Code Editor:

Previous: Write a NumPy program to copy data from a given array to another array.
Next: Write a NumPy program to swap columns in a given array.

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.