如何使用Python在图表中找到最近的坐标

问题描述 投票:0回答:2

我想使用其坐标值(x,y)找到最近的图形点。我的数据集就像

-15907.500 -19367.500
-15912.500 -19362.500
-15907.500 -19362.500
-15917.500 -19357.500
-15912.500 -19357.500
-15917.500 -19352.500
-15912.500 -19352.500 
-16092.500 -19347.500 

例如,我们可以把任何一点作为参考,通过这个参考,我们必须找到最接近的近距离和另一个小的距离坐标。

python python-3.x numpy
2个回答
1
投票
data
      cols    cols1
0 -15907.5 -19367.5
1 -15912.5 -19362.5
2 -15907.5 -19362.5
3 -15917.5 -19357.5
4 -15912.5 -19357.5
5 -15917.5 -19352.5
6 -15912.5 -19352.5
7 -16092.5 -19347.5
from sklearn.metrics.pairwise import euclidean_distances
euclidean_distances(data)
array([[  0.        ,   7.07106781,   5.        ,  14.14213562,
         11.18033989,  18.02775638,  15.8113883 , 186.07794066],
       [  7.07106781,   0.        ,   5.        ,   7.07106781,
          5.        ,  11.18033989,  10.        , 180.62391868],
       [  5.        ,   5.        ,   0.        ,  11.18033989,
          7.07106781,  14.14213562,  11.18033989, 185.60711193],
       [ 14.14213562,   7.07106781,  11.18033989,   0.        ,
          5.        ,   5.        ,   7.07106781, 175.28548143],
       [ 11.18033989,   5.        ,   7.07106781,   5.        ,
          0.        ,   7.07106781,   5.        , 180.27756377],
       [ 18.02775638,  11.18033989,  14.14213562,   5.        ,
          7.07106781,   0.        ,   5.        , 175.071414  ],
       [ 15.8113883 ,  10.        ,  11.18033989,   7.07106781,
          5.        ,   5.        ,   0.        , 180.06943105],
       [186.07794066, 180.62391868, 185.60711193, 175.28548143,
        180.27756377, 175.071414  , 180.06943105,   0.        ]])

参考:-

  1. Eucledian_distance

0
投票

要计算两点之间的(欧几里德)距离,您只需减去它们的坐标,平方,加,取平方根。换一种说法:

def distance_between(x1, y1, x2, y2):
    return sqrt((x1-x2)**2 + (y1-y2)**2)

方便的是,math模块提供了为我们执行此操作的函数hypot(因为它使用C,因此效率更高)。

所以现在我们可以这样做:

from math import hypot

def closest_to(data, target):
    x, y = target # Break `target` into coordinates

    def distance(other_point): # How far is `other_point` from `target`?
        x2, y2 = other_point # Break `other_point` into coordinates
        return hypot(x-x2, y-y2) # Then calculate distance

    return min(data, key=distance) # Now run through `data` and return whichever one has the lowest `distance` result
© www.soinside.com 2019 - 2024. All rights reserved.