【问题标题】:Python how to create a new column that measures proximity to a city?Python如何创建一个衡量与城市接近程度的新列?
【发布时间】:2020-08-15 16:52:16
【问题描述】:

我有一个包含纬度和经度列的数据框,

df = pd.DataFrame({'Latitude':[47.5112, 47.7210, 47.7379, 47.5208, 47.6168],
                    'Longitude':[-122.257, -122.319, -122.233, -122.393, -122.045]})

如何使用坐标(47.631872,-122.217109)创建一个列来测量到特定位置的距离

我特别想使用geopy 中的geodesic 函数来表示距离:from geopy.distance import geodesic。它接受包含纬度和经度的2个元组的输入,并输出距离。

【问题讨论】:

    标签: python pandas geolocation geopy


    【解决方案1】:

    使用apply

    location = (47.631872, -122.217109)
    df["distance"] = df.apply(lambda x:geodesic((x["Latitude"], x["Longitude"]), location), axis=1)
    

    【讨论】:

    • 我觉得应该是location = (47.631872, -122.217109)<br> df["distance"] = df.apply(lambda x:geodesic((x["Latitude"], x["Longitude"]), location), axis=1)
    • @spidermarn 你是对的,这是另一种选择,希望这次你能得到你需要的东西
    • @spidermarn 按照您的建议更新。
    【解决方案2】:

    假设您想在 DataFrame 中创建一个具有所需距离的新列:

    location = (40.5, 47.7) # example of coordinates of your desired location, change as needed
    
    df["Distance To Location"] = geodesic((df["Latitude"],df["Longitude"]),location)
    
    

    您的数据框现在将具有第 3 列,其中包含指向来自每个纬度/经度行和位置坐标的 pandas 系列测地线对象的指针。

    如果您只想以“英里”表示实际距离值(浮点数),您可以执行以下操作:

    # To get the float value of the distance in miles
    df["Distance To Location"] = geodesic((df["Latitude"],df["Longitude"]),location).miles
    

    它应该将每行的浮点值(以英里为单位)直接保存到您的数据框中。

    【讨论】:

    • 检查您是否有 NaN 或空的 Lat/long 值,可能需要先清理/删除这些值。
    • 你运行的是什么版本的 pandas 和 python?
    • 不要认为是版本问题,虽然我使用的是python 3.8.1,但是pandas 1.0.3,那么你是将测地线对象存储在列中还是转换为英里或公里值?我不使用测地线,但使用自定义类进行了测试并且没有问题,您是否也尝试过 applylambda 函数,正如其他答案所暗示的那样?
    • 另外,你确定你没有在其中添加额外的布尔逻辑,比如“and”/“or”吗?因为这将是您得到一系列模棱两可的真值类型错误的主要原因。
    • applylambda 的另一个答案对我有用
    猜你喜欢
    • 2012-02-24
    • 2018-05-05
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    相关资源
    最近更新 更多