【问题标题】:Calculate distance between two coordinates for a fixed point in a DataFrame计算DataFrame中固定点的两个坐标之间的距离
【发布时间】:2023-01-26 20:33:19
【问题描述】:

我在熊猫中有以下数据框:

code latitude longitude
01 40.410323 -3.993046
02 41.490604 1.696572
03 39.287817 -0.435448
04 38.594316 -0.128489
05 36.900799 -3.423063
06 36.541667 -4.625

我想创建一个名为 km_to_fixed_coords 的新列,其中计算到新固定点的坐标距离,这对于所有行 (36.7196, -4.42002) 都是相同的。

此代码计算两个坐标之间的距离(以公里为单位)。

import geopy.distance
# (latitude, longitude)
coords_1 = (x, y)
fixed_coords = (36.7196, -4.42002)

print(geopy.distance.distance(coords_1, fixed_coords).km)

生成的 DataFrame 应类似于示例:

code latitude longitude km_to_fixed_coords
01 40.410323 -3.993046 411.3819700981563
02 41.490604 1.696572 748.2482442578678
03 39.287817 -0.435448 451.2806740048897
04 38.594316 -0.128489 432.0145327165797
05 36.900799 -3.423063 91.20470627900332
06 36.541667 -4.625342 26.96511660526825

【问题讨论】:

    标签: python pandas dataframe geopy


    【解决方案1】:
    from typing import Tuple
    import geopy.distance
    
    
    def distance(
        lat: float, lon: float, fixed_coords: Tuple[float] = (36.7196, -4.42002)
    ) -> float:
        return geopy.distance.distance((lat, lon), fixed_coords).km
    
    
    df["km_to_fixed_coords"] = df.apply(lambda row: distance(row.latitude, row.longitude))
    

    【讨论】:

      【解决方案2】:

      在这样的行上应用方法?

      import geopy.distance
      
      # (latitude, longitude)
      fixed_coords = (36.7196, -4.42002)
      
      df['km_to_fixed_coords'] = df.apply(
          lambda row: geopy.distance.distance((row.latitude, row.longitude), fixed_coords).km,
          axis=1
      )
      

      【讨论】:

        【解决方案3】:

        从 django.contrib.gis.geos 导入点

        #当前位置(经度,纬度)
        当前坐标 = 点 (-3.993046, 40.410323 )
        #目标位置(经度,纬度)
        target_coord = 点 (1.696572, 41.490604 )
        #计算公里距离
        距离 = current_coord.distance(target_coord) * 100

        【讨论】: