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>I would recommande using a quicker variation of looping through a df such has</p>

<pre><code>df_shift = df.shift(1)
df = df.join(df_shift, l_suffix="lag_")
log = []

for rows in df.itertuples():
     log.append(haversine(rows.lng ,rows.lat, rows.lag_lng, rows.lag_lat))

pd.DataFrame(log)
</code></pre>

python pandas