python - 在 NumPy 数组中查找索引的值和 n 个最近的邻居
问题描述
我想知道是否有人能告诉我如何找到一个数字的索引和NumPy
数组中最近的 n 个邻居的索引。
例如,在这个数组中,我想找到 value 的索引87
,以及它的四个最近的邻居86
,88
左边和78
右边43
。
a = np.random.randint(1,101,15)
array([79, 86, 88, 87, 78, 43, 57])
解决方案
如果您想不时更改值,尽管这对于大型数组来说会很昂贵,但应该这样做:
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),您应该这样做。
然后,从结果中删除数字。其余的将是您想要的邻居。
推荐阅读
- rxjs - Observable 中的 RxJs 包装函数
- java - Docker Container javax.mail.MessagingException:没有合适的协议(协议被禁用或密码套件不合适);
- java - 我正在尝试初始化子类中的基类属性,但出现错误
- python - 如何在保持索引不变的同时基于列创建新行?
- python - python - Selenium Stackoverflow 机器人
- javascript - 重复表单的 AJAX 保存
- powershell - Powershell控制台缓冲区中随机出现神秘空白
- sql - 我必须更新 SQL Server 中的 4000 万行
- javascript - 在父母的构造函数中将道具传递给孩子
- sql - SQL UPDATE 中是否有隐式 JOIN 的概念?