2014-09-10 99 views
5

我知道,要找到兩個緯度,經度點之間的距離,我需要使用半正矢函數:矢量化haversine公式與大熊貓據幀

def haversine(lon1, lat1, lon2, lat2): 
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) 
    dlon = lon2 - lon1 
    dlat = lat2 - lat1 
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2 
    c = 2 * asin(sqrt(a)) 
    km = 6367 * c 
    return km 

我有一個數據幀,其中一列是緯度和另一列是經度。我想知道這些點距離設定點有多遠,-56.7213600,37.2175900。我如何從DataFrame中取值並將它們放入函數中?

例如數據框:

 SEAZ  LAT   LON 
1 296.40, 58.7312210, 28.3774110 
2 274.72, 56.8148320, 31.2923240 
3 192.25, 52.0649880, 35.8018640 
4  34.34, 68.8188750, 67.1933670 
5 271.05, 56.6699880, 31.6880620 
6 131.88, 48.5546220, 49.7827730 
7 350.71, 64.7742720, 31.3953780 
8 214.44, 53.5192920, 33.8458560 
9  1.46, 67.9433740, 38.4842520 
10 273.55, 53.3437310, 4.4716664 
+0

我已經發布了一個答案,可以解決您的問題,但我認爲這不是最佳的 – EdChum 2014-09-10 14:16:20

+0

對於一個小的df,我的答案可以,但是對於更大的df,您最好將度數轉換爲弧度並存儲然後在整個數據幀上執行計算 – EdChum 2014-09-10 14:22:51

+0

我在df中有143個值,並且這似乎運行良好。 – user3755536 2014-09-10 14:31:12

回答

16

我無法證實,如果計算是正確的,但下面的工作:

In [11]: 

def haversine(row): 
    lon1 = -56.7213600 
    lat1 = 37.2175900 
    lon2 = row['LON'] 
    lat2 = row['LAT'] 
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) 
    dlon = lon2 - lon1 
    dlat = lat2 - lat1 
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2 
    c = 2 * arcsin(sqrt(a)) 
    km = 6367 * c 
    return km 

df['distance'] = df.apply(lambda row: haversine(row), axis=1) 
df 
Out[11]: 
     SEAZ  LAT  LON  distance 
index           
1  296.40 58.731221 28.377411 6275.791920 
2  274.72 56.814832 31.292324 6509.727368 
3  192.25 52.064988 35.801864 6990.144378 
4  34.34 68.818875 67.193367 7357.221846 
5  271.05 56.669988 31.688062 6538.047542 
6  131.88 48.554622 49.782773 8036.968198 
7  350.71 64.774272 31.395378 6229.733699 
8  214.44 53.519292 33.845856 6801.670843 
9  1.46 67.943374 38.484252 6418.754323 
10  273.55 53.343731 4.471666 4935.394528 

下面的代碼是在這麼小的數據幀實際上慢,但我申請它達到100,000行df:

In [35]: 

%%timeit 
df['LAT_rad'], df['LON_rad'] = np.radians(df['LAT']), np.radians(df['LON']) 
df['dLON'] = df['LON_rad'] - math.radians(-56.7213600) 
df['dLAT'] = df['LAT_rad'] - math.radians(37.2175900) 
df['distance'] = 6367 * 2 * np.arcsin(np.sqrt(np.sin(df['dLAT']/2)**2 + math.cos(math.radians(37.2175900)) * np.cos(df['LAT_rad']) * np.sin(df['dLON']/2)**2)) 

1 loops, best of 3: 17.2 ms per loop 

相比於花費4.3s的apply函數所以快了近250倍,一些在未來

注意,如果我們壓縮到一個班輪上述所有:

In [39]: 

%timeit df['distance'] = 6367 * 2 * np.arcsin(np.sqrt(np.sin((np.radians(df['LAT']) - math.radians(37.21759))/2)**2 + math.cos(math.radians(37.21759)) * np.cos(np.radians(df['LAT']) * np.sin((np.radians(df['LON']) - math.radians(-56.72136))/2)**2))) 
100 loops, best of 3: 12.6 ms per loop 

我們現在觀察到進一步加快UPS倍〜快341倍。

+0

感謝您進行優化比較。良好的工作。 – deepelement 2017-08-08 14:14:44