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?
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...
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With