返回数据框中最接近用户定义数字的行 [英] return rows in a dataframe closest to a user-defined number

查看:55
本文介绍了返回数据框中最接近用户定义数字的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户定义的编号,我想将其与数据框的特定列进行比较.

I have a user defined number which I want to compare to a certain column of a dataframe.

我想返回一个数据框的行,这些行包含(在df的某个列中,例如df.num)与给定数字x最接近的5个数字.

I would like to return the rows of a dataframe which contain (in a certain column of df, say, df.num) the 5 closest numbers to the given number x.

任何不使用循环的最佳方法的建议,将不胜感激.

Any suggestions for the best way to do this without loops would be greatly appreciated.

推荐答案

我认为您可以使用

I think you can use the argsort method:

>>> df = pd.DataFrame({"A": 1e4*np.arange(100), "num": np.random.random(100)})
>>> x = 0.75
>>> df.ix[(df.num-x).abs().argsort()[:5]]
         A       num
66  660000  0.748261
92  920000  0.754911
59  590000  0.764449
27  270000  0.765633
82  820000  0.732601
>>> x = 0.33
>>> df.ix[(df.num-x).abs().argsort()[:5]]
         A       num
37  370000  0.327928
76  760000  0.327921
8    80000  0.326528
17  170000  0.334702
96  960000  0.324516

这篇关于返回数据框中最接近用户定义数字的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆