Dataframe groupby.apply with multiple arguments pandas python
<p>I have a dataframe like the one below and i'm trying to calculate the distance between two points in multiple gps trips using a haversine formula that has 4 inputs. So basically grouping on trip_id and applying the haversine formula. </p>

<p>I had thought something like <code>df['distance'] = df.groupby('trip_id').apply(haversine, df.lng, df.lat, df.lnglag_, df.latlag_)</code> would work but I get <code>TypeError: haversine() takes 4 positional arguments but 5 were given</code>. Any ideas on what is going on here?</p>

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

<p>Where the haversine formula is something I got from the web.</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
    m = km/1000
    return m
</code></pre>

<p>I would use numpy vectorize method such has</p>

<pre><code>import numpy as np   
np.vectorize(haversine)(df.lng, df.lat, df.lnglag_, df.latlag_)
</code></pre>

python pandas