Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the index of a Numpy Array

I have a numpy array:

arr = [0.23, 2.32, 4.04, 5.02, 6.84, 10.12, 10.34, 11.93,12.44]

I want to get the index of the closest integer I enter. For example if I enter 10 then I should get back index 5 (10.12) or if I enter 12 i should get back index 7 (11.93).

like image 450
magicsword Avatar asked Jan 24 '26 12:01

magicsword


1 Answers

If your list isn't sorted, you will need a linear time solution using abs + argmin:

>>> np.abs(np.array(arr) - 12).argmin()
7

However, if your list is sorted (ascending or descending), you can employ binary search for a sub-linear time solution (very fast):

# https://ideone.com/aKEpI2 — improved by @user2357112
def binary_search(arr, val):
    # val must be in the closed interval between arr[i-1] and arr[i],
    # unless one of i-1 or i is beyond the bounds of the array.
    i = np.searchsorted(arr, val)

    if i == 0:
        # Smaller than the smallest element
        return i
    elif i == len(arr):
        # Bigger than the biggest element
        return i - 1
    elif val - arr[i - 1] <= arr[i] - val:
        # At least as close to arr[i - 1] as arr[i]
        return i - 1

    # Closer to arr[i] than arr[i - 1]
    return i

cases = [10, 12, 100, 10.12]   # 5, 7, 8, 5
print(*[binary_search(arr, c) for c in cases], sep=',')
like image 84
cs95 Avatar answered Jan 27 '26 00:01

cs95



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!