NumPy: Find elements within range from a given array of numbers
Find Elements in a Specified Range
Write a NumPy program to find elements within a range from a given array of numbers.
Sample Solution:
Python Code:
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:
For more Practice: Solve these Related Problems:
- Write a NumPy program to filter an array and return the indices of elements within a specified numerical range.
- Create a function that uses np.where to find elements between two thresholds and validates the output.
- Test the range filter on arrays with both positive and negative numbers to ensure comprehensive coverage.
- Implement an alternative solution using boolean masking to directly extract the values in the specified range.
Go to:
PREV : Copy Data to Another Array
NEXT : Swap Columns in 2D Array
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.