简体   繁体   English

找到第二个最接近的索引值

[英]Find the second closest index to value

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? 但是,有没有一个很好的干净方式,比如找到第二个最接近该值的索引?

You can get the index of the kth smallest element of an array a without sorting the whole array using argpartition 您可以使用argpartition数组a的第k个最小元素的索引,而无需对整个数组进行argpartition

np.argpartition(a, k)[k]

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...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM