emremrah
emremrah

Reputation: 1765

Check if a given value is between any of the numbers in a given array

Consider the given array:

import numpy as np
borders = np.array([[ 7848, 10705],
                    [10861, 13559],
                    [13747, 16319],
                    [16792, 19427],
                    [19963, 22535]])

How can I check if a given value is between any of these intervals?

I defined a custom function like:

def _if_between(value, arr):
    for borders in arr:
        if borders[0] <= value <= borders[1]:
            return True

    return False

And it works. Is there a more neat way to do that? Maybe using numpy, or a.any() etc.?

Expected outpus:

Upvotes: 1

Views: 398

Answers (6)

Meow
Meow

Reputation: 1267

Pandas 1.0.3 has an IntervalArray type which has a contains method to check if a number exists in any interval in the array:

import pandas as pd

borders = [
    [ 7848, 10705],
    [10861, 13559],
    [13747, 16319],
    [16792, 19427],
    [19963, 22535]
]
intervals = pd.arrays.IntervalArray.from_tuples(borders)
result = intervals.contains(19426)

result variable will look as follows:

array([False, False, False,  True, False])

Upvotes: 0

DJSchaffner
DJSchaffner

Reputation: 582

Using pure Python without any modules and using any plus list comprehension:

# Assumes borders is an array of pairs
def _if_between(value, borders):
  return any( [min <= value and max >= value for min, max in borders] )

Upvotes: 1

Josh Clark
Josh Clark

Reputation: 1012

Here's a slight improvement:

def _if_between(value, arr):
        if any([borders[0] <= value <= borders[1] for borders in arr]):
            return True
        return False

Upvotes: 1

ParthS007
ParthS007

Reputation: 2691

You can just check by this simple approach:

def _if_between(value, arr):
    for borders in arr:
        return value in range(borders[0], borders[1])

Upvotes: 2

Doing it on pure Python is better. But you can your code faster than a simple loop.

value = 10869
[True if border[0] <= value <= border[1] else False for border in borders]

Upvotes: 0

FBruzzesi
FBruzzesi

Reputation: 6475

If you don't need to know which index the element is in you can vectorize the loop as:

import numpy as np

def _if_between(value, arr):
    return np.any( np.logical_and(borders[:,0] <= value, value <=borders[:,1]))

Upvotes: 2

Related Questions