Iterate over Pandas index pairs [0,1],[1,2][2,3]
<p>I have a pandas dataframe of lat/lng points created from a gps device. </p>

<p>My question is how to generate a distance column for the distance between each point in the gps track line. </p>

<p>Some googling has given me the haversine method below which works using single values selected using <code>iloc</code>, but i'm struggling on how to iterate over the dataframe for the method inputs.</p>

<p>I had thought I could run a for loop, with something along the lines of </p>

<pre><code>for i in len(df):
    df['dist'] = haversine(df['lng'].iloc[i],df['lat'].iloc[i],df['lng'].iloc[i+1],df['lat'].iloc[i+1]))
</code></pre>

<p>but I get the error <code>TypeError: 'int' object is not iterable</code>. I was also thinking about <code>df.apply</code> but I'm not sure how to get the appropriate inputs. Any help or hints. on how to do this would be appreciated.</p>

<p>Sample DF</p>

<pre><code>       lat        lng
0 -7.11873  113.72512
1 -7.11873  113.72500
2 -7.11870  113.72476
3 -7.11870  113.72457
4 -7.11874  113.72444
</code></pre>

<p>Method</p>

<pre><code>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(math.radians, [lon1, lat1, lon2, lat2])
    # haversine formula 
    dlon = lon2 - lon1 
    dlat = lat2 - lat1 
    a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
    c = 2 * math.asin(math.sqrt(a)) 
    km = 6367 * c
    return km
</code></pre>

<p>are you looking for a result like this?</p>

<pre><code>       lat        lon  dist2next
0 -7.11873  113.72512   0.013232
1 -7.11873  113.72500   0.026464
2 -7.11873  113.72476   0.020951
3 -7.11873  113.72457   0.014335
4 -7.11873  113.72444        NaN
</code></pre>

<p>There's probably a clever way to use pandas.rolling_apply...  but for a quick solution, I'd do something like this.</p>

<pre><code>def haversine(loc1, loc2):
    # convert decimal degrees to radians 
    lon1, lat1 = map(math.radians, loc1)
    lon2, lat2 = map(math.radians, loc2)

    # haversine formula 
    dlon = lon2 - lon1 
    dlat = lat2 - lat1 
    a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
    c = 2 * math.asin(math.sqrt(a)) 
    km = 6367 * c
    return km

df['dist2next'] = np.nan
for i in df.index[:-1]:
  loc1 = df.ix[i,   ['lon', 'lat']]
  loc2 = df.ix[i+1, ['lon', 'lat']]
  df.ix[i, 'dist2next'] = haversine(loc1, loc2)
</code></pre>

<p>alternatively, if you don't want to modify your haversine function like that, you can just pick off lats and lons one at a time using df.ix[i, 'lon'], df.ix[i, 'lat'], df.ix[i+1, 'lon], etc.</p>

python pandas