第一个数据帧 df1 包含 id 及其对应的两个坐标。对于第一个数据帧中的每个坐标对,我必须循环遍历第二个数据帧以找到距离最小的一个。我尝试获取各个坐标并找到它们之间的距离,但它没有按预期工作。我相信在计算它们之间的距离时必须将其视为一对。不确定Python是否提供了一些方法来实现这一点。
例如:df1
Id Co1 Co2
334 30.371353 -95.384010
337 39.497448 -119.789623
df2
Id Co1 Co2
339 40.914585 -73.892456
441 34.760395 -77.999260
dfloc3 =[[38.991512-77.441536],
[40.89869-72.37637],
[40.936115-72.31452],
[30.371353-95.38401],
[39.84819-75.37162],
[36.929306-76.20035],
[40.682342-73.979645]]
dfloc4 = [[40.914585,-73.892456],
[41.741543,-71.406334],
[50.154522,-96.88806],
[39.743565,-121.795761],
[30.027597,-89.91014],
[36.51881,-82.560844],
[30.449587,-84.23629],
[42.920475,-85.8208]]
最佳答案
鉴于您可以将您的积分放入这样的列表中......
df1 = [[30.371353, -95.384010], [39.497448, -119.789623]]
df2 = [[40.914585, -73.892456], [34.760395, -77.999260]]
导入数学,然后创建一个函数,以便更轻松地计算距离:
import math
def distance(pt1, pt2):
return math.sqrt((pt1[0] - pt2[0])**2 + (pt1[1] - pt2[1])**2)
然后简单地横切你的列表,保存最近的点:
for pt1 in df1:
closestPoints = [pt1, df2[0]]
for pt2 in df2:
if distance(pt1, pt2) < distance(closestPoints[0], closestPoints[1]):
closestPoints = [pt1, pt2]
print ("Point: " + str(closestPoints[0]) + " is closest to " + str(closestPoints[1]))
输出:
Point: [30.371353, -95.38401] is closest to [34.760395, -77.99926]
Point: [39.497448, -119.789623] is closest to [34.760395, -77.99926]
关于python - 计算坐标对之间的最小距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39044599/