繁体   English   中英

如何在 dataframe 列 pandas 中找到最接近所选数字的 5 个数字的索引?

[英]How to find the index of 5 numbers nearest to a chosen number in a dataframe column pandas?

假设我的 x 列有 1-9 的九个数字。 如果我选择 4,我将在 x 中获得 1、2、3、4、5 的索引,因为 4 是最接近 4 的数字,然后 1、2、3、5 是下一个最接近 4 的数字。我看了看与此类似的帖子,但它没有说明最接近自身的数字。 这是我目前拥有的,但我想知道是否可以添加一些东西来解释我提到的最后一个测试用例。

df_sort = df.iloc[(df['x']-xseq).abs().argsort()[:6]]
index = df_sort.index.tolist()

设置

df = pd.DataFrame({'x': range(1, 10)})

nsmallest

df.loc[df.x.sub(4).abs().nsmallest(5).index]

   x
3  4
2  3
4  5
1  2
5  6

Numpy 的argpartition

df.iloc[np.argpartition(np.abs(df.x.to_numpy() - 4), 5)[:5]]

   x
5  6
4  5
2  3
3  4
1  2

暂无
暂无

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

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