寻找第二个最接近价值的指数 [英] Find the second closest index to value
本文介绍了寻找第二个最接近价值的指数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用
index = (np.abs(array - value)).argmin()
在数组中找到与值具有最小绝对差的索引.
to find the index in an array with the smallest absolute difference to a value.
但是,有没有一种类似的好方法可以找到与该值最接近的 second 索引?
However, is there a nice clean way such as this for finding the second closest index to the value?
推荐答案
我认为这可行
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...
这篇关于寻找第二个最接近价值的指数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文