Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the second closest index to value

Tags:

python

numpy

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?

like image 923
Aphire Avatar asked Apr 17 '15 10:04

Aphire


2 Answers

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...
like image 186
plonser Avatar answered Nov 01 '22 15:11

plonser


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]
  • http://docs.scipy.org/doc/numpy/reference/generated/numpy.argpartition.html
like image 35
YXD Avatar answered Nov 01 '22 13:11

YXD