Python 如何创建一个新列来衡量与城市的距离?

Python how to create a new column that measures proximity to a city?

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

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 个元组的输入,并输出距离。

假设您想在 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 系列测地线对象的指针,每个 lat/long 行和所提供的位置坐标。

可选地,如果您只想要实际距离值(浮点数),例如“英里”,您可以这样做:

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

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

使用apply

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