title: Fast Haversine Approximation (Python/Pandas)
body: <p>Each row in a Pandas dataframe contains lat/lng coordinates of 2 points. Using the Python code below, calculating the distances between these 2 points for many (millions) of rows takes a very long time!</p>
  
  <p>Considering that the 2 points are under 50 miles apart and accuracy is not very important, is it possible to make the calculation faster?</p>
  
  <pre><code>from math import radians, cos, sin, asin, sqrt
  def haversine(lon1, lat1, lon2, lat2):
      """
      Calculate the great circle distance between two points 
      on the earth (specified in decimal degrees)
      """
      # convert decimal degrees to radians 
      lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
      # haversine formula 
      dlon = lon2 - lon1 
      dlat = lat2 - lat1 
      a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
      c = 2 * asin(sqrt(a)) 
      km = 6367 * c
      return km
  
  
  for index, row in df.iterrows():
      df.loc[index, 'distance'] = haversine(row['a_longitude'], row['a_latitude'], row['b_longitude'], row['b_latitude'])
  </code></pre>