How to print array elements within a given range using Numpy?

PythonNumpyServer Side ProgrammingProgramming

In this program, we have to print elements of a numpy array in a given range. The different numpy functions used are numpy.where() and numpy.logical_and().

Algorithm

Step 1: Define a numpy array.
Step 2: Use np.where() and np.logical_and() to find the numbers within the given range.
Step 3: Print the result.

Example Code

import numpy as np

arr = np.array([1,3,5,7,10,2,4,6,8,10,36])
print("Original Array:\n",arr)

result = np.where(np.logical_and(arr>=4, arr<=20))
print(result)

Output

Original Array:
[ 1  3  5  7 10  2  4  6  8 10 36]
(array([2, 3, 4, 6, 7, 8, 9], dtype=int64),)

Explanation

The result gives the index positions of elements which satisfy the condition in the np.where() function.

raja
Published on 16-Mar-2021 10:34:06
Advertisements