[英]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
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.