【问题标题】:Python - Calculating distances from two different list of long/latPython - 从两个不同的长/纬度列表计算距离
【发布时间】:2020-03-24 14:15:22
【问题描述】:

我有两个带有经度和纬度坐标的数据框。 df1 有 20 个坐标,df2 有 600 个坐标。我正在尝试做的是获取 df1 中的每个坐标并在 df 中找到最近的坐标。例如,df1 中的第一个坐标是 52.2296756、21.0122287,所以我必须以某种方式创建循环以获取这两个值并计算 df2 中每个坐标的距离并返回距离最短的那个。

到目前为止我有这个代码:

import geopy.distance
import pandas as pd

coords_1 = (52.2296756, 21.0122287)
coords_2 = (52.406374, 16.9251681)

print(geopy.distance.vincenty(coords_1, coords_2).km)

我将如何编写此函数以从 df1 获取第一个坐标并对 df 中的每个坐标执行计算并返回最接近的坐标?

【问题讨论】:

    标签: python pandas geopy


    【解决方案1】:

    好吧,你可以遍历你的数据框并一一计算距离,但如果你有更大的数据,我不建议这样做。

    # Find the minimum distances
    min_distances = []
    longitudes = []
    latitudes = []
    
    for index1, row1 in df1.iterrows():
      coords_1 = (row1['longitude'], row1['latitude'])
      min_distance = 0
      long = 0
      lat = 0
    
      for index2, row2 in df2.iterrows():
        coords_2 = (row2['longitude'], row2['latitude'])
    
        if min_distance == 0: 
          min_distance = geopy.distance.vincenty(coords_1, coords_2).km
          continue
    
        distance = geopy.distance.vincenty(coords_1, coords_2).km
        if distance < min_distance:
          min_distance = distance
          long = row2['longitude']
          lat = row2['latitude']
    
      min_distances.append(min_distance)
      longitudes.append(long)
      latitudes.append(lat)
    
    # Create a column based on the result
    df1['min_distance'] = min_distances
    df1['long'] = longitudes
    df1['lat'] = latitudes
    

    【讨论】:

    • 感谢您的建议,但是这会返回距离,而不是 df2 中的哪个坐标最接近 df1 中的坐标。因此,我希望获得最接近的坐标,而不是距离。
    • 好吧,你可以只添加最小距离的经度和纬度,我编辑了代码,让我知道这是否适合你
    猜你喜欢
    • 2018-06-11
    • 2020-05-09
    • 1970-01-01
    • 2017-06-26
    • 1970-01-01
    • 2012-10-13
    • 2016-06-27
    • 1970-01-01
    • 2014-04-10
    相关资源
    最近更新 更多