Home > Enterprise >  how to use a function to calculate the distance between two cities
how to use a function to calculate the distance between two cities

Time:01-14

I need to write a function to calculate the distance between two cities.

import pandas as pd
from geopy import distance
capitals = pd.read_csv('https://raw.githubusercontent.com/j-rossi-nl/teaching-    data/main/2022_ITP/concap.csv')
capitals.head(5)
capitals.set_index('CapitalName', inplace = True)
capitals.loc["Amsterdam"]
def cities_distance(city_from: str, city_to: str = 'Amsterdam', cities: pd.DataFrame = capitals)->float:

I don't know how to select the capitallatitude and longitude when using geopy to calculate the distance. It needs to return the distance in kilometers.

CodePudding user response:

IIUC, you can use geopy.distance.geodesic. Below, a proposition based on your code :

import pandas as pd
from geopy.distance import geodesic

capitals = pd.read_csv("https://raw.githubusercontent.com/j-rossi-nl/teaching-data/main/2022_ITP/concap.csv",
                       index_col="CapitalName")

def cities_distance(city_from: str, city_to: str = "Amsterdam", cities: pd.DataFrame = capitals)->float:
    lat_long = ["CapitalLatitude", "CapitalLongitude"]

    origin = capitals.loc[city_from, lat_long].agg(tuple)
    destination = capitals.loc[city_to, lat_long].agg(tuple)

    return round(geodesic(origin,destination).km,2)

We use here pandas.DataFrame.loc with pandas.Series.agg to form a tuple with the coordinatees of the origin capital and pass it as a keyword argument to geodesic :

Parameters
point : (geopy.point.Point), list or tuple of (latitude, longitude), or string as "%(latitude)s, %(longitude)s".) – Starting point.

NB : The Geodesic distance will give a measure of the shortest path between the two capitals.

Output :

cities_distance("Hargeisa")
#5912.67

CodePudding user response:

In conjuntion with shapely.Geometry and pyproj.Geod

geometry_length Returns the geodesic length (meters) of the shapely geometry

from pyproj import Geod
from shapely.geometry import Point, LineString
import pandas as pd
capitals = pd.read_csv("https://raw.githubusercontent.com/j-rossi-nl/teaching-data/main/2022_ITP/concap.csv",
                       index_col="CapitalName")

line_string = LineString([Point(capitals['CapitalLongitude'].iloc[0], capitals['CapitalLatitude'].iloc[0]), Point(capitals['CapitalLongitude'].iloc[1], capitals['CapitalLatitude'].iloc[1])])
geod = Geod(ellps="WGS84")

print(f"{geod.geometry_length(line_string):.3f}")
#10255732.456

print(f"{geod.geometry_length(line_string)/1000:.3f}") # k/m
#10255.732
  • Related