python - 返回数据框中最接近用户定义数字的行

标签 python python-2.7 pandas

我有一个用户定义的数字,我想将它与数据框的某一列进行比较。

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

任何关于没有循环的最佳方法的建议将不胜感激。

最佳答案

我认为您可以使用 argsort方法:

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

关于python - 返回数据框中最接近用户定义数字的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17758023/

相关文章:

python - 如何在 VS 代码中获得 VS 的 python 语法高亮显示?

使用 Arduino 的 Python 脚本无法正确读取数据

python - 将字典转储为 json 文件作为 UTF-8

python-2.7 - 导入错误 : No module named time

python - findall 和 xpath 问题

python - 如何比较 DataFrame 的 3 列,Python 3.6

python - %(something)s 是什么意思?

python-2.7 - Pandas / python : split column based on a dictionary

python - 如何为数据帧的每一行应用一个函数,该函数检查嵌入字典的键

python - Pandas - 取消堆叠/使用多个索引进行透视