我有两组数组,我要寻找的是array2中与array1中每个值最近的点的索引,例如:
import numpy as np
from scipy.spatial import distance
array1 = np.array([[1,2,1], [4,2,6]])
array2 = np.array([[0,0,1], [4,5,0], [1,2,0], [6,5,0]])
def f(x):
return distance.cdist([x], array2 ).argmin()
def array_map(x):
return np.array(list(map(f, x)))
array_map(array1)
此代码返回正确的结果,但是当两个数组都很大时速度很慢。我想知道是否可以更快地做到这一点?
答案 0 :(得分:1)
感谢@ Max7CD,这是一个可以有效工作的解决方案(至少出于我的目的):
from scipy import spatial
tree =spatial.KDTree(array2)
slitArray = np.split(array1, 2) #I split the data so that the KDtree doesn't take for ever and so that I can moniter progress, probably useless
listFinal = []
for elem in slitArray:
a = tree.query(elem)
listFinal.append(a[1])
print("Fnished")
b = np.array(listFinal).ravel()