- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Find elements within range in numpy in Python

Sometime while processing data using the numpy library, we may need to filter out certain numbers in a specific range. This can be achieved by using some in-built methods available in numpy.

## With and operator

In this approach we take an numpy array then apply the logical_and function to it. The where clause in numpy is also used to apply the and condition. The result is an array showing the position of the elements satisfying the required range conditions.

import numpy as np A = np.array([5, 9, 11, 4, 31, 27,8]) # printing initial array print("Given Array : ", A) # Range 6 to 15 res = np.where(np.logical_and(A >= 6, A <= 15)) # Result print("Array with condition : ", res)

## Output

Running the above code gives us the following result −

Given Array : [ 5 9 11 4 31 27 8] Array with condition : (array([1, 2, 6], dtype=int32),)

## Using *

In this approach we use the * operator. It gives the result as actual values instead of the position of the values in the array.

import numpy as np A = np.array([5, 9, 11, 4, 31, 27,8]) # printing initial array print("Given Array : ", A) # Range 6 to 15 res = A [ (A >=6) * (A <= 15)] # Result print("Array with condition : ", res)

## Output

Running the above code gives us the following result −

Given Array : [ 5 9 11 4 31 27 8] Array with condition : [ 9 11 8]

- Related Questions & Answers
- How to print array elements within a given range using Numpy?
- Program to find number of pairs where elements square is within the given range in Python
- How to create a numpy array within a given range?
- How to find Kaprekar numbers within a given range using Python?
- Delete elements in range in Python
- Python – Filter Strings within ASCII range
- Python Program to replace list elements within a range with a given number
- Python - Find the number of prime numbers within a given range of numbers
- Find missing elements of a range in C++
- Prime numbers within a range in JavaScript
- Armstrong number within a range in JavaScript
- Assign range of elements to List in Python
- Python – Extract tuples with elements in Range
- Find smallest range containing elements from k lists in C++
- Python – Filter Rows with Range Elements

Advertisements