ComplicatedPhenomenon
ComplicatedPhenomenon

Reputation: 4189

find the array index which its element is most near greater than a value

I have a sorted array.

x = [1, 10, 12, 16, 19, 20, 21, ....]

for any given number y which is between [x[0], x[-1]], I want to find the index of the element which is the most near greater than y, for example, if y = 0, it returns 0, if y = 18, it returns 4

Is there a function available?

Upvotes: 2

Views: 74

Answers (3)

Crikxi
Crikxi

Reputation: 71

Without any external library, you can use bisect

i = bisect.bisect_right(x, y)

i will be the index of the element you wanted.

Upvotes: 3

Divakar
Divakar

Reputation: 221574

Given the sorted nature, we can use np.searchsorted -

idx = np.searchsorted(x,y,'right')

Upvotes: 2

FBruzzesi
FBruzzesi

Reputation: 6495

You can use numpy.argmin on the absolute value of the difference:

import numpy as np
x = np.array([1, 10, 12, 16, 19, 20, 21])

def find_closest(x,y):
    return (np.abs(x-y)).argmin()

for y in [0,18]:
    print(find_closest(x,y))

0
4

Upvotes: 1

Related Questions