Reputation: 27
So I have a task about create haversine function that takes two parameters which are two points on the earth and calculates distance between each other and finally returns this distance as an integer value.
cities = [{"name": "Buenos Aires", "lat": -34.58333333, "lon": -58.666667},
{"name": "Vienna", "lat": 48.2, "lon": 16.366667},
{"name": "Baku", "lat": 40.38333333, "lon": 49.866667},
{"name": "Beijing", "lat": 39.91666667, "lon": 116.383333},
{"name": "Paris", "lat": 48.86666667, "lon": 2.333333},
{"name": "Berlin", "lat": 52.51666667, "lon": 13.4},
{"name": "Dublin", "lat": 53.31666667, "lon": -6.233333},
{"name": "Mexico City ", "lat": 19.43333333, "lon": -99.133333},
{"name": "Lisbon", "lat": 38.71666667, "lon": -9.133333},
{"name": "Washington", "lat": 38.883333, "lon": -77},
{"name": "Ankara", "lat": 39.93333333, "lon": 32.866667}
]
I need to put those latitude and longitude values in this Haversine formula
distance = 2 * r * asin(sqrt(sin((lat2 - lat1) / 2) ** 2 + cos(lat1) * cos(lat2) * sin((lon2 - lon1) / 2)) ** 2)
And have an example output like in this image:
I need help in selecting two different latitude and longitude values and putting them in lat2 lat1 lon2 lon1. Thank you.
Upvotes: 0
Views: 927
Reputation: 2659
# import packages
from sklearn.metrics.pairwise import haversine_distances
from math import radians
import pandas as pd
# create a list of names and radians
city_names = []
city_radians = []
for c in cities:
city_names.append(c['name'])
city_radians.append([radians(c['lat']), radians(c['lon'])])
# calculate the haversine distance
result = haversine_distances(city_radians)
# multiply by the Earth radius to get kilometers
result *= 6371000/1000
# show the result as a pandas dataframe
df = pd.DataFrame(result, columns= city_names, index= city_names)
df
optional: you can also cast results into integers if you don't need floats
Upvotes: 2