[英]Pandas / Python: Groupby.apply() with function dictionary
[英]Dataframe groupby.apply with multiple arguments pandas python
我有一個像下面這樣的數據框,我正在嘗試使用具有4個輸入的Haversine公式來計算多次GPS行程中兩點之間的距離。 因此,基本上將trip_id分組並應用haversine公式。
我曾以為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
我在網上從哪里得到了haversine公式。
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
我會使用numpy vectorize這樣的方法
import numpy as np
np.vectorize(haversine)(df.lng, df.lat, df.lnglag_, df.latlag_)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.