【问题标题】:How to find the distance between two points given longitude and latitude without do loop?如何在没有循环的情况下找到给定经度和纬度的两点之间的距离?
【发布时间】:2019-07-12 11:24:05
【问题描述】:

我有两个给定经度和纬度的位置,我想在 python 中获取这些点之间的距离。我的数据集如下所示:

 df_TEST = pd.DataFrame({'Location': ['X1','X2'],
                     'Long': [ 28.63615701706,76],
                     'Lat': [ 41.0693487044612,54],
                     'Location1': ['Y1','Y2'],
                     'Long1': [30.7158891385255,65],
                     'Lat1': [36.963486025471,45]}) 

我想用下面的代码向这个数据框添加一个新列,但它只适用于一行。我有一个庞大的数据集,我想在没有循环的情况下添加此列。建议的解决方案来自 How to find the distance between two points given longitude and latitude in python-error? 我该怎么做?

 df_TEST['distance']=geopy.distance.geodesic(float(df_TEST['Long'] . 
[0]), float(df_TEST['Lat'][0]),(float(df_TEST['Long1'] . 
[0]),float(df_TEST['Lat1'][0]))).km

【问题讨论】:

    标签: python distance latitude-longitude


    【解决方案1】:

    您可以在 DataFrame 上使用 apply() 函数,将函数应用于 DataFrame 的每一行。

    代码如下:

    def distance(row):
        return (geopy.distance.geodesic((row['Long'], row['Lat']), 
                                         row['Long1'], row['Lat1']).km)
    
    df_TEST['distance']=df_TEST.apply(distance, axis=1)
    

    【讨论】:

      【解决方案2】:

      我可能错过了一些东西,但是呢

      >>> df_TEST['distance_km'] = df_TEST.apply(
              lambda r: geopy.distance.geodesic(
                  r.Long, r.Lat,  r.Long1, r.Lat1
              ).km,
              axis=1
          )
      >>> df_TEST
        Location       Long        Lat Location1      Long1       Lat1  distance_km
      0       X1  28.636157  41.069349        Y1  30.715889  36.963486  3221.113126
      1       X2  76.000000  54.000000        Y2  65.000000  45.000000  5904.462593
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-13
        • 1970-01-01
        • 2014-08-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多