将 2D numpy 数组排序到每个元素与某个点的接近程度

Am1*_*3zA 6 python arrays sorting numpy

我有 (n,2) numpy 数组,其中包含 n 个点的坐标,现在我想根据每个元素与特定点 (x,y) 的近似值对它们进行排序,并选择最接近的一个。我怎样才能做到这一点?

现在我有:

def find_nearest(array,value):
    xlist = (np.abs(array[:, 0]-value[:, 0]))
    ylist = (np.abs(array[:, 1]-value[:, 1]))
    newList = np.vstack((xlist,ylist))
    // SORT NEW LIST and return the 0 elemnt
Run Code Online (Sandbox Code Playgroud)

在我的解决方案中,我需要根据 (0,0) 的接近度对 newList 进行排序,但我不知道如何?这个或任何其他解决方案的任何解决方案?

我的点数组看起来像:

array([[ 0.1648,  0.227 ],
       [ 0.2116,  0.2472],
       [ 0.78  ,  0.546 ],
       [ 0.9752,  1.    ],
       [ 0.384 ,  0.4862],
       [ 0.4428,  0.2204],
       [ 0.4448,  0.4146],
       [ 0.1046,  0.2658],
       [ 0.5668,  0.7792],
       [ 0.1664,  0.0746],
       [ 0.5636,  0.6372],
       [ 0.7822,  0.5536],
       [ 0.7718,  0.8276],
       [ 0.9916,  1.    ],
       [ 0.    ,  0.    ],
       [ 0.8206,  0.817 ],
       [ 0.4858,  0.4652],
       [ 0.    ,  0.    ],
       [ 0.1574,  0.3114],
       [ 0.    ,  0.0022],
       [ 0.874 ,  0.714 ],
       [ 0.148 ,  0.6624],
       [ 0.0656,  0.5912],
       [ 0.1148,  0.607 ],
       [ 0.069 ,  0.6296]])
Run Code Online (Sandbox Code Playgroud)

650*_*502 6

排序以找到最近的点不是一个好主意。如果你想要最近的点,那么只需找到最近的点,对它进行排序是多余的。

def closest_point(arr, x, y):
    dist = (arr[:, 0] - x)**2 + (arr[:, 1] - y)**2
    return arr[dist.argmin()]
Run Code Online (Sandbox Code Playgroud)

此外,如果您需要使用一组固定或准固定的点多次重复搜索,则有特定的数据结构可以大大加快此类查询的速度(搜索时间变为次线性)。


Dan*_*iel 2

如果您只想要笛卡尔距离,您可以执行以下操作:

def find_nearest(arr,value):
    newList = arr - value
    sort = np.sum(np.power(newList, 2), axis=1)
    return newList[sort.argmin()]
Run Code Online (Sandbox Code Playgroud)

我假设newList形状为 (n,2)。请注意,我将输入变量更改array为 ,arr以避免在导入 numpy 时出现问题from numpy import *