【问题标题】:Calculating distance of latitude/longitude on pandas dataframe using GeoPy使用 GeoPy 计算 pandas 数据帧上的纬度/经度距离
【发布时间】:2020-08-04 20:26:55
【问题描述】:

我正在尝试使用 Pandas Dataframe 上的 geopy 计算纬度和经度之间的距离。

这是我的数据框:

    latitude    longitude   altitude
    -15.836310  -48.020298  1137.199951
    -15.836360  -48.020512  1136.400024
    -15.836415  -48.020582  1136.400024
    -15.836439  -48.020610  1136.400024
    -15.836488  -48.020628  1136.599976

我尝试了两种不同的方法:

from geopy import distance

for i in range(1, len(df)):
   before = (df.loc[i-1, 'latitude'], df.loc[i-1, 'longitude'])
   actual = (df.loc[i, 'latitude'], df.loc[i, 'longitude'])
   df.loc[i, 'geodesic'] = distance.distance(before, actual).miles

错误:

 KeyError: 0

显然,df.loc[i, 'column_name'] 不起作用。

和:

from geopy import distance

df['geodesic'] = distance.distance((df.latitude.shift(1), df.longitude.shift(1)), (df.latitude, df.longitude)).miles

错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

官方 GeoPy 文档:

from geopy import distance
newport_ri = (41.49008, -71.312796)
cleveland_oh = (41.499498, -81.695391)
print(distance.distance(newport_ri, cleveland_oh).miles)

【问题讨论】:

    标签: python pandas geopy


    【解决方案1】:
    raw = """latitude;longitude;altitude
    -15.836310;-48.020298;1137.199951
    -15.836360;-48.020512;1136.400024
    -15.836415;-48.020582;1136.400024
    -15.836439;-48.020610;1136.400024
    -15.836488;-48.020628;1136.599976"""
    
    import pandas as pd
    from io import StringIO
    from geopy import distance
    
    data = StringIO(raw)
    df = pd.read_csv(data, sep=";")
    df1 = df.drop(['altitude'], axis=1)
    locations = df1.apply(tuple, axis=1)
    
    for counter in range(len(locations) - 1):
        print(distance.distance(locations[counter], locations[counter + 1]).miles)
    

    来自df = pd.read_csv(data, sep=";") 和你的代码一样,我让它可测试。

    之后,df1 = df.drop(['altitude'], axis=1) 删除表格 z 轴,在此应用程序中不需要。

    将 df1 转换为元组,然后循环遍历位置,你就得到了你的距离

    【讨论】:

      【解决方案2】:

      我收到了错误。

      1 - 我必须检查 latitudelongitude 是否为 NaN

      2 - 我无法将 time 设置为索引。 (我不知道为什么,这花了很长时间才发现)

      一旦检查,错误就消失了。

      【讨论】:

        猜你喜欢
        • 2018-09-07
        • 2016-03-15
        • 1970-01-01
        • 2013-04-16
        • 1970-01-01
        • 1970-01-01
        • 2021-09-05
        • 1970-01-01
        • 2021-05-10
        相关资源
        最近更新 更多