Python有效地找到一个坐标数组的最接近的值

问题描述 投票:1回答:1

我有两组数组,我正在寻找的是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)

此代码返回正确的结果,但是当两个数组都非常大时,它会很慢。我想知道是否可以更快地制作这个?

python numpy coordinates
1个回答
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()
© www.soinside.com 2019 - 2024. All rights reserved.