首页 > 解决方案 > 在 NumPy 数组中查找索引的值和 n 个最近的邻居

问题描述

我想知道是否有人能告诉我如何找到一个数字的索引和NumPy数组中最近的 n 个邻居的索引。

例如,在这个数组中,我想找到 value 的索引87,以及它的四个最近的邻居8688左边和78右边43

a = np.random.randint(1,101,15)
array([79, 86, 88, 87, 78, 43, 57])

标签: pythonarraysnumpy

解决方案


如果您想不时更改值,尽管这对于大型数组来说会很昂贵,但应该这样做:

a = np.array([79, 86, 88, 87, 78, 43, 57])

number = 87
n_nearest = 4

index = np.where(a == number)[0][0] # np.where returns (array([3]),)

a = a[max(0, index - n_nearest // 2):index + n_nearest // 2 + 1]
nearests = np.delete(a, n_nearest // 2)

print(nearests)

输出:[86 88 78 43]

首先,找到您获得邻居的值的索引(尽管可能不适用于重复值)。

max(0, index - 2)如果您想要的值可能位于数组的开头(位置 0 或 1),您应该这样做。

然后,从结果中删除数字。其余的将是您想要的邻居。


推荐阅读