首页 > 解决方案 > python从两个表中找到最近的点并打印对名称

问题描述

嗨,我是 python 新手,在查看我的问题的解决方案时,我只从一个列表中找到了选择。在我的情况下有两张桌子

表格1:

表格1

表 2:

表 2

我想从两个表中选择最接近的点对,并作为输出获取对的列表。谁能帮助我?

标签: pythonpandas

解决方案


我假设您想要 table1 中的一个点和 table2 中最接近的一个点。

你可以试试这个。。

import math

# finds the Euclidean distance
def getDistance(x1,y1,x2,y2):
    return math.sqrt((x1-x2)**2+(y1-y2)**2)

#finds the closest points from table1 and table2
def getClosestPoints(table1, table2):
    #pointA, pointB
    distance = None
    for x1,y1 in zip(table1['x'], table1['y']):
        for x2, y2 in zip(table2['x'], table2['y']):
            dis = getDistance(x1,y1,x2,y2)
            #print (f"x1 = {x1}, y1 = {y1}, x2 = {x2}, y2 = {y2} | dis = {dis}")
            if distance == None or distance > dis:
                distance = dis
                pointA = (x1,y1)
                pointB = (x2,y2)
                #print(f"A={pointA}, B={pointB}, dis = {distance}")
            else:
                continue
    return pointA, pointB, distance

返回点 1、点 2 和距离。

print(getClosestPoints(table1, table2))

输出:((41.31175,15.1337),(41.55,14.96778),0.2903317221730979)

即 ((x1, y1), (x2, y2), 距离)


推荐阅读