0

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?

zcoop98
  • 2,590
  • 1
  • 18
  • 31
Romain
  • 135
  • 9
  • What do you mean by "A numpy array with identical values"? Could you also elaborate on your what your question/problem is? Do you mean you want to find the indices of all of the values in a list that are "close" to a given number? – Ewan Brown Jan 06 '22 at 16:58

2 Answers2

0
>> 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]

0

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)