如何在 Pandas 系列中找到与输入数字最接近的值? [英] How do I find the closest values in a Pandas series to an input number?
本文介绍了如何在 Pandas 系列中找到与输入数字最接近的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我见过:
这些与 vanilla python 而不是 pandas 相关.
These relate to vanilla python and not pandas.
如果我有这个系列:
ix num
0 1
1 6
2 4
3 5
4 2
然后我输入了 3,我怎样才能(有效地)找到?
- 如果在系列中找到它的索引为 3
- 如果在系列中没有找到低于和高于 3 的值的索引.
即.使用上述系列 {1,6,4,5,2} 和输入 3,我应该得到带有索引 (2,4) 的值 (4,2).
Ie. With the above series {1,6,4,5,2}, and input 3, I should get values (4,2) with indexes (2,4).
推荐答案
你可以像使用 argsort()
一样
比如说,input = 3
In [198]: input = 3
In [199]: df.iloc[(df['num']-input).abs().argsort()[:2]]
Out[199]:
num
2 4
4 2
df_sort
是具有 2 个最接近值的数据框.
df_sort
is the dataframe with 2 closest values.
In [200]: df_sort = df.iloc[(df['num']-input).abs().argsort()[:2]]
对于索引,
In [201]: df_sort.index.tolist()
Out[201]: [2, 4]
对于值,
In [202]: df_sort['num'].tolist()
Out[202]: [4, 2]
<小时>
细节,对于上述解决方案df
是
In [197]: df
Out[197]:
num
0 1
1 6
2 4
3 5
4 2
这篇关于如何在 Pandas 系列中找到与输入数字最接近的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文