0

I try to calculate distances between two points in spherical coord.

There are two latitude and longitude array which size is around 1100000

lat = [-10, 10, 1, 82, ..., -72]
lon = [120, -58, 13, 22, ..., 122]

Also, there is a standard point

loc_lat = -60
loc_lon = -50

so I try to calculate using below code, but It takes too much time. Is there any efficient way ?

from geopy import distance    
D_from_loc = [distance.distance((lat[i], lon[i]), (loc_lat, loc_lon)).km for i in range(len(lon))]
이원석
  • 87
  • 2
  • 5

1 Answers1

0

sklearn implementations is quite fast;

import numpy as np
from sklearn.metrics import pairwise_distances
size = 1100000
X = np.random.random( (size,2))
Y = np.array([[-60,-50]])

radians_X = np.radians(X)
radians_Y = np.radians(Y)

result = pairwise_distances(radians_X,radians_Y, metric='haversine')
result * 6371000/1000  # multiply by Earth radius to get kilometers

This will take <1 second. Make sure to test if you have lat/long order right, which for sklearn is (lat,long) pairs. Also, the result might slightly differ from other implementations, as the earth needs to be approximated as a big sphere. The choose of the exact radius has (small) impact.

Willem Hendriks
  • 1,267
  • 2
  • 9
  • 15