Dataframe groupby.apply有多个参数pandas python

时间:2016-10-04 00:11:55

标签: python pandas

我有一个类似下面的数据框,我正在尝试使用具有4个输入的hasrsine公式计算多个gps行程中两个点之间的距离。所以基本上分组trip_id并应用半正式公式。

我原以为像df['distance'] = df.groupby('trip_id').apply(haversine, df.lng, df.lat, df.lnglag_, df.latlag_)这样的东西会起作用,但我得TypeError: haversine() takes 4 positional arguments but 5 were given。关于这里发生了什么的任何想法?

    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

如果我从网上得到了哈克思公式。

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

1 个答案:

答案 0 :(得分:0)

我会使用numpy vectorize方法,如

import numpy as np   
np.vectorize(haversine)(df.lng, df.lat, df.lnglag_, df.latlag_)