23 lines
884 B
Python
23 lines
884 B
Python
import numpy as np
|
|
import pandas as pd
|
|
from pyproj import Geod
|
|
|
|
def closest_city(point, df=None, population_threshold=0):
|
|
|
|
"""Get the name, population, and distance to the point of the closest city"""
|
|
|
|
if df is None:
|
|
df = pd.read_csv("africapolis.csv", index_col=0)
|
|
df = df[df["Population"] > population_threshold]
|
|
geod = Geod(ellps="WGS84")
|
|
pos = df.apply(lambda row: geod.inv(point[1], point[0], row["Longitude"], row["Latitude"]), axis=1)
|
|
fwd_azimuth, distances = pos.apply(lambda row: row[0]), pos.apply(lambda row: row[2])
|
|
min_index = distances.idxmin()
|
|
city = df.loc[min_index]
|
|
return {
|
|
"name": city["Name"],
|
|
"population": np.int64(city["Population"]),
|
|
"distance": np.float64(distances[min_index]),
|
|
"location": (city["Latitude"], city["Longitude"]),
|
|
"fwd_azimuth": fwd_azimuth[min_index],
|
|
} |