Gmaps距离矩阵:如何迭代数据帧中的行序列并计算距离

2024-06-12 00:16:39 发布

您现在位置:Python中文网/ 问答频道 /正文

请看附件快照,我问我的问题。 我有一个数据帧,其中一对纬度/经度是从不同程序进行地理编码的,我正在尝试生成(纬度1/经度1)和(纬度2/经度2)之间的距离矩阵,以找出位置之间的距离。在

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

   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)

预期产量

^{pr2}$

数据帧

 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

Tags: 数据import程序距离sourcedataframedfdestination
1条回答
网友
1楼 · 发布于 2024-06-12 00:16:39

我没有使用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

现在我们需要合并2个数据帧More detail here

^{pr2}$

接下来,您需要将其应用于每一行

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

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

我还想补充一下,如果这是完整的代码,那么实际上并没有向数据帧添加任何数据。在

相关问题 更多 >