I have a numpy array with repeated values
array = np.array([1,2,3,4,5,1,2,3,4,5])
I would like to find indices for a closest value, e.g 3.3
I think I need to use numpy.argmin
but I do not know how to do that.
Could someone help me?
I have a numpy array with repeated values
array = np.array([1,2,3,4,5,1,2,3,4,5])
I would like to find indices for a closest value, e.g 3.3
I think I need to use numpy.argmin
but I do not know how to do that.
Could someone help me?
>> import numpy as np
>> value_search = 3.3
>> array = np.array([1,2,3,4,5,1,2,3,4,5])
You should use np.argsort
: the closet one is 2nd index (number 3) then 7th (number 3 as well) then ...
>> np.argsort(abs(array - value_search))
array([2, 7, 3, 8, 1, 6, 4, 9, 0, 5]
To find the first value that is closest to your input, you could look at the index where the absolute difference is lowest. Something like so:
closest_idx = np.abs(array - 3.3).argmin()
To then find the indices of all values that have the same (closest) value:
closest_val = array[min_idx]
all_closest_idx = np.argwhere(array == closest_val)