Skip to content

Instantly share code, notes, and snippets.

@gthank
Created September 16, 2016 11:44
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 gthank/7cab3dea45e4c8ee07758c34ae329956 to your computer and use it in GitHub Desktop.
Save gthank/7cab3dea45e4c8ee07758c34ae329956 to your computer and use it in GitHub Desktop.
numpy-based method for calculating (great circle) distance between two series of points.
import numpy as np
import pandas as pd
from geopy.distance import EARTH_RADIUS
def numpy_distance(src_lats, src_longs, dest_lats, dest_longs):
"""Calculate distance between (effectively) two Series of points."""
# Convert from degrees to radians.
src_lats = src_lats.apply(np.deg2rad)
src_longs = src_longs.apply(np.deg2rad)
dest_lats = dest_lats.apply(np.deg2rad)
dest_longs = dest_longs.apply(np.deg2rad)
# grab sines
src_lat_sin = src_lats.apply(np.sin)
dest_lat_sin = dest_lats.apply(np.sin)
# grab cosines
src_lat_cos = src_lats.apply(np.cos)
dest_lat_cos = src_lats.apply(np.cos)
lng_deltas = dest_longs.subtract(src_longs)
lng_delta_cos = lng_deltas.apply(np.cos)
lng_delta_sin = lng_deltas.apply(np.sin)
return EARTH_RADIUS * np.arctan2(
np.sqrt(
(dest_lat_cos * lng_delta_sin) ** 2 +
(src_lat_cos * dest_lat_sin - src_lat_sin * dest_lat_cos * lng_delta_cos) ** 2
),
src_lat_sin * dest_lat_sin + src_lat_cos * dest_lat_cos * lng_delta_cos
)
# NOTE: parcel_info is a dataframe I read in from some 100MB+ CSV file. Hooray public data projects!
num_rows = parcel_info.shape[0]
numpy_distance(
parcel_info['Latitude'],
parcel_info['Longitude'],
pd.Series(np.repeat(42.420167, num_rows)),
pd.Series(np.repeat(-82.968060, num_rows))
)
@nick-stang
Copy link

I believe you have a typo in you function on line 17

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment