【问题标题】:Gmaps Distance Matrix : How to iterate over sequence of rows in data frame and calculate distance地图距离矩阵:如何迭代数据框中的行序列并计算距离
【发布时间】:2019-07-05 21:27:35
【问题描述】:

当我问我的问题时,请查看随附的快照。 我有一个数据框,其中包含一对从不同程序进行地理编码的纬度/经度,我正在尝试生成(Latitude1/Longitude1)和(Latitude2/Longitude2)之间的距离矩阵等以查找位置之间的距离。

我下面的程序似乎没有读取所有行。

   import pandas as pd
   import googlemaps
   import requests, json

   gmaps = googlemaps.Client(key='123)

   source = pd.DataFrame({'Latitude': df['Latitude1'] ,'Longitude': df['Longitude1']})
   destination = pd.DataFrame({'Latitude': df['Latitude2'] ,'Longitude': df['Longitude2']})

   source = source.reset_index(drop=True)
   destination = destination.reset_index(drop=True)

   for i in range(len(source)):
   result = gmaps.distance_matrix(source, destination)
   print(result)

预期输出

   Distance
   12 Miles
   10 Miles
   5 Miles
   1 Mile

数据帧

 Key Latitude1  Longitude1   Latitude2    Longitude#2
 1    42             -91          40           -92
 2    39             -94.35       38           -94
 3    37             -120         36           -120
 4    28.7           -90          35           -90
 5    40             -94          38           -90
 6    30             -90          25           -90

【问题讨论】:

    标签: python pandas google-maps google-distancematrix-api


    【解决方案1】:

    我没有用过 gmap,但这是一个计算距离的简单公式。
    这只是数学,所以我不会在这里解释。 只知道您需要 2 个格式为 (lat, lon) 的位置作为参数,并且需要导入数学

    def distance(origin, destination):
        lat1, lon1 = origin
        lat2, lon2 = destination
        radius = 3959 # mi
    
        dlat = math.radians(lat2-lat1)
        dlon = math.radians(lon2-lon1)
        a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) \
            * math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2)
        c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
        d = radius * c
    
        return d
    

    现在我们需要合并两个数据框More detail here

     maindf = pd.merge(source, destination , left_index=True, right_index=True)
    

    接下来你需要将它应用到每一行

    maindf['Distance'] = maindf.apply(lambda row: distance((row.Latitude1,row.Longditude1),(row.Latitude2,row.Longditude2)), axis=1)
    

    在数据帧上应用循环并应用函数。
    在这种情况下,它根据每行中的 2 个纬度/经度对将“距离”应用于每一行。
    这会添加一个新列“距离”,其中包含两个位置之间的距离(以英里为单位)。

    我还要补充一点,如果这是您的完整代码,您实际上并没有向数据帧添加任何数据。

    【讨论】:

    • 虽然这是正确的,但它没有考虑到现实世界的变量,例如道路、建筑物等等。我认为使用 gmaps api 会更好。
    猜你喜欢
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    • 2017-11-15
    相关资源
    最近更新 更多