Reputation: 939
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.
Upvotes: 1
Views: 744
Reputation: 7693
Use apply
location = (47.631872, -122.217109)
df["distance"] = df.apply(lambda x:geodesic((x["Latitude"], x["Longitude"]), location), axis=1)
Upvotes: 2
Reputation: 114
Assuming you want to create a new column within the DataFrame with the desired distance:
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)
Your dataframe will now have a 3rd column with a pointer to a pandas Series of geodesic objects from each lat/long row and location coordinates provided.
Optionally if you only want the actual distance value (float) in say "miles" you can do something like this:
# To get the float value of the distance in miles
df["Distance To Location"] = geodesic((df["Latitude"],df["Longitude"]),location).miles
And it should save the float value in miles for each row directly into your dataframe.
Upvotes: 1