Skip to content
Advertisement

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

I have a dataframe with Latitude and Longitude columns,

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]})

How do I create a column that measures the distance towards a particular location with coordinates (47.631872, -122.217109)

In particular I’d like to use the geodesic function from geopy for the distance: from geopy.distance import geodesic. It takes in the inputs of 2 tuples containing latitudes and longitudes, and outputs the distance.

Advertisement

Answer

Use apply

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

Advertisement