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

Python Gmaps距离矩阵:如何迭代数据帧中的行序列并计算距离,python,pandas,google-maps,google-distancematrix-api,Python,Pandas,Google Maps,Google Distancematrix Api,当我提问时,请参阅附件中的快照。 我有一个带有一对纬度/经度的数据帧,这些纬度/经度是从不同的程序中地理编码的,我正在尝试生成(纬度1/经度1)和(纬度2/经度2)之间的距离矩阵,以此类推,以查找位置之间的距离 我下面的程序似乎没有读取所有行 import pandas as pd import googlemaps import requests, json gmaps = googlemaps.Client(key='123) source = pd.Dat

当我提问时,请参阅附件中的快照。 我有一个带有一对纬度/经度的数据帧,这些纬度/经度是从不同的程序中地理编码的,我正在尝试生成(纬度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)
预期产量 数据帧
我没有使用GMAP,但这是一个计算距离的简单公式。
这只是数学,所以我不在这里解释。 只需知道格式中需要两个位置(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
现在我们需要合并这两个数据帧

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

maindf['Distance'] = maindf.apply(lambda row: distance((row.Latitude1,row.Longditude1),(row.Latitude2,row.Longditude2)), axis=1)
在数据帧上应用循环并应用函数。
在这种情况下,基于每行中的2个横向/纵向对,将“距离”应用于每行。
这将添加一个新列“距离”,其中两个位置之间的距离以英里为单位


我还想补充一点,如果这是您的完整代码,您实际上不会向数据帧添加任何数据

虽然这是正确的,但它没有考虑现实世界的变量,比如道路、建筑物等等。我认为使用GMAPSAPI会更好。
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
 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)