9

I am using

index = (np.abs(array - value)).argmin()

to find the index in an array with the smallest absolute difference to a value.

However, is there a nice clean way such as this for finding the second closest index to the value?

Aphire
  • 1,621
  • 25
  • 55
  • I would doubt it, to be honest! You could get sorted differences and index the second smallest. – jonrsharpe Apr 17 '15 at 10:27
  • What should be returned if two indexes are equally close to the value? – Alex Riley Apr 17 '15 at 10:29
  • @ajcr, Well I guess the second value to be picked would be the one that argmin() didn't choose (I don't know how argmin() goes about choosing in the first place) – Aphire Apr 17 '15 at 10:31

2 Answers2

14

I think this works

a = np.linspace(0,10,30)
array([  0.        ,   0.34482759,   0.68965517,   1.03448276,
         1.37931034,   1.72413793,   2.06896552,   2.4137931 ,
         2.75862069,   3.10344828,   3.44827586,   3.79310345,
         4.13793103,   4.48275862,   4.82758621,   5.17241379,
         5.51724138,   5.86206897,   6.20689655,   6.55172414,
         6.89655172,   7.24137931,   7.5862069 ,   7.93103448,
         8.27586207,   8.62068966,   8.96551724,   9.31034483,
         9.65517241,  10.        ])
n = np.pi
a[np.argsort(np.abs(a-n))[1]]
# Output 3.4482758620689657
# the closest value is 3.103...
plonser
  • 3,323
  • 2
  • 18
  • 22
14

You can get the index of the kth smallest element of an array a without sorting the whole array using argpartition

np.argpartition(a, k)[k]
YXD
  • 31,741
  • 15
  • 75
  • 115
  • 3
    This is certainly preferable for large arrays as it is `O(n)` in complexity (while regular full-sorting is typically `O(n*log(n))`) (+1). – Alex Riley Apr 17 '15 at 11:42
  • Luckily the array is not very large at all, so I am using the above answer and its working, but thanks for providing a more efficient way, I have some large data sets this might be helpful for – Aphire Apr 17 '15 at 13:12
  • What is `a`? What is `k`? How to implement it to solve OP question? Lots of question appears and your link about the documents also did not provide for the exact same question from the OP. – Muhammad Yasirroni Sep 23 '21 at 14:32