在多个 numpy 数组中找到最近的集合

Find the nearest set in multiple numpy arrays

我有 3 个 numpy 数组,即 xyz,每个数组的长度相等。此外,3 个 numpy 数组之间的匹配索引形成一个集合,例如(x[i],y[i],z[i])。给定 xyz 作为已知数组和任意目标集,例如a = [0.0,1.0,2.0],是否有一种有效的 numpy-thonic 方法来计算索引 i,在 xyz 中找到最接近的单个集合a?

我不认为在这种情况下使用基本 Python 解决方案是 'un-numpy-thonic':

import numpy as np

x = np.array([1, 2, 2, 3, 2])
y = np.array([4, 4, 5, 6, 5])
z = np.array([7, 8, 8, 9, 8])

a = (2, 5, 8)

first_match = next(n for n, t in enumerate(zip(x, y, z)) if t == a)
all_matches = [n for n, t in enumerate(zip(x, y, z)) if t == a]
print(first_match, all_matches)

结果:

2 [2, 4]

您可以利用 numpy 矢量化,

import numpy as np

all_indices = np.random.randint(0,100,size=(100,3))
target = np.array([1.3,4.5,10])

dist = np.linalg.norm(all_indices-target,axis=1)
closest_ind = np.argmin(dist)

更新

上面的解决方案可以像这样推广到多个目标

import numpy as np

all_indices = np.random.randint(0,100,size=(100,3))

all_indices = all_indices[:,None,:]
target = np.array([[1.3,4.5,10],[1.3,15,8],[20,6,10],[1.3,15,8]])
dist = np.linalg.norm(all_indices-target,axis=2).T
closest_ind = np.argmin(dist,axis=1)