Skip to content

Instantly share code, notes, and snippets.

@SebastianoF
Created April 24, 2022 16:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SebastianoF/d6285d7eed3a83341d1158bcccfd75c1 to your computer and use it in GitHub Desktop.
Save SebastianoF/d6285d7eed3a83341d1158bcccfd75c1 to your computer and use it in GitHub Desktop.
b001_12.py
from typing import Tuple
from math import radians
def haversine(lng1: float, lat1: float, lng2: float, lat2: float) -> Tuple[float, float]:
""" returns (haversine distance in km, bearing in degrees from point 1 to point 2), vectorised """
avg_earth_radius_km = 6371.0072
lng1, lat1, lng2, lat2 = map(np.deg2rad, [lng1, lat1, lng2, lat2])
d_lat, d_lng = lat2 - lat1, lng2 - lng1
d = np.sin((d_lat)/2)**2 + np.cos(lat1)*np.cos(lat2) * np.sin((d_lng)/2)**2
hav_dist = 2 * avg_earth_radius_km * np.arcsin(np.sqrt(d))
y = np.sin(d_lng) * np.cos(lat2)
x = np.cos(lat1) * np.sin(lat2) - np.sin(lat1) * np.cos(lat2) * np.cos(d_lng)
bearing = (np.arctan2(y, x) + 2 * np.pi) % (2 * np.pi)
return hav_dist, np.rad2deg(bearing)
def add_bearing_deg_and_distance_km(df: pd.DataFrame) -> pd.DataFrame:
"""bearing between A and B is the angle between the geodesics connecting A and the north pole, and the geodesics connecting A and B.
Both the bearing and distance are computed on the Spherical model.
"""
df = df.copy()
lng_work, lat_work = df.workplace_lng.to_numpy(), df.workplace_lat.to_numpy()
lng_home, lat_home = df.residence_lng.to_numpy(), df.residence_lat.to_numpy()
df["distance_km"], df["bearing_deg"] = haversine(lng_work, lat_work, lng_home, lat_home)
return df
df_commuters_st_luke_office = add_bearing_deg_and_distance_km(df_commuters_st_luke_office)
df_commuters_albert_road = add_bearing_deg_and_distance_km(df_commuters_albert_road)
df_commuters_st_luke_office.head()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment