title: Vectorizing Haversine distance calculation in Python
body: <p>I am trying to calculate a distance matrix for a long list of locations identified by Latitude &amp; Longitude using the <a href="https://github.com/mapado/haversine" rel="noreferrer">Haversine</a> formula that takes two tuples of coordinate pairs to produce the distance:</p>
  
  <pre><code>def haversine(point1, point2, miles=False):
      """ Calculate the great-circle distance bewteen two points on the Earth surface.
  
      :input: two 2-tuples, containing the latitude and longitude of each point
      in decimal degrees.
  
      Example: haversine((45.7597, 4.8422), (48.8567, 2.3508))
  
      :output: Returns the distance bewteen the two points.
      The default unit is kilometers. Miles can be returned
      if the ``miles`` parameter is set to True.
  
      """
  </code></pre>
  
  <p>I can calculate the distance between all points using a nested for loop as follows:</p>
  
  <pre><code>data.head()
  
     id                      coordinates
  0   1   (16.3457688674, 6.30354512503)
  1   2    (12.494749307, 28.6263955635)
  2   3    (27.794615136, 60.0324947881)
  3   4   (44.4269923769, 110.114216113)
  4   5  (-69.8540884125, 87.9468778773)
  </code></pre>
  
  <p>using a simple function:</p>
  
  <pre><code>distance = {}
  def haver_loop(df):
      for i, point1 in df.iterrows():
          distance[i] = []
          for j, point2 in df.iterrows():
              distance[i].append(haversine(point1.coordinates, point2.coordinates))
  
      return pd.DataFrame.from_dict(distance, orient='index')
  </code></pre>
  
  <p>But this takes quite a while given the time complexity, running at around 20s for 500 points and I have a much longer list. This has me looking at vectorization, and I've come across <code>numpy.vectorize</code> (<a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.vectorize.html" rel="noreferrer">(docs)</a>, but can't figure out how to apply it in this context. </p>