2016-04-25 22 views
5

我有2個數據框正在使用。一個有一堆位置和座標(經度,緯度)。另一個是天氣數據集,其中包含來自世界各地氣象站的數據和它們各自的座標。我正嘗試將最近的氣象站連接到我的數據集中的每個位置。氣象站名稱和我的位置名稱不匹配。如何根據從一個數據框到另一個數據框的2個鍵找到最接近的匹配項?

我試圖通過座標中最接近的匹配來連接它們,並且不知道從哪裏開始。

我在想一些使用每個

位置

np.abs((location['latitude']-weather['latitude'])+(location['longitude']-weather['longitude'])

例子的...

Location Latitude Longitude Component \ 
    A 39.463744 -76.119411 Active 
    B 39.029252 -76.964251 Active 
    C 33.626946 -85.969576 Active 
    D 49.286337 10.567013 Active 
    E 37.071777 -76.360785 Active 

天氣...

 Station Code    Station Name Latitude Longitude 
    US1FLSL0019 PORT ST. LUCIE 4.0 NE 27.3237 -80.3111 
    US1TXTV0133   LAKEWAY 2.8 W 30.3597 -98.0252 
    USC00178998     WALTHAM 44.6917 -68.3475 
    USC00178998     WALTHAM 44.6917 -68.3475 
    USC00178998     WALTHAM 44.6917 -68.3475 

輸出將是位置數據框上的一個新列,與站名最接近匹配

但是,我不確定如何通過循環來實現這一點。任何幫助將不勝感激..

感謝, 斯科特

+0

你能給出你的2個data.frames和期望的輸出樣本嗎? –

+1

除非你特別想用python來做,否則你應該考慮使用postGIS查詢,它們對你的情況來說可以非常快。 – CoderBC

+0

經過更新以反映每個數據幀的樣本以及期望的輸出 – sokeefe1014

回答

4

比方說你有,你希望儘量減少距離函數dist

def dist(lat1, long1, lat2, long2): 
    return np.abs((lat1-lat2)+(long1-long2)) 

對於給定的位置,你可以找到最近的車站如下:

lat = 39.463744 
long = -76.119411 
weather.apply(
    lambda row: dist(lat, long, row['Latitude'], row['Longitude']), 
    axis=1) 

這將計算到所有氣象站的距離。使用idxmin你可以找到最近的車站名稱:

distances = weather.apply(
    lambda row: dist(lat, long, row['Latitude'], row['Longitude']), 
    axis=1) 
weather.loc[distances.idxmin(), 'StationName'] 

讓我們把所有的功能:

def find_station(lat, long): 
    distances = weather.apply(
     lambda row: dist(lat, long, row['Latitude'], row['Longitude']), 
     axis=1) 
    return weather.loc[distances.idxmin(), 'StationName'] 

現在,您可以通過它應用到locations數據框得到所有的最近的車站:

locations.apply(
    lambda row: find_station(row['Latitude'], row['Longitude']), 
    axis=1) 

輸出:

0   WALTHAM 
1   WALTHAM 
2 PORTST.LUCIE 
3   WALTHAM 
4 PORTST.LUCIE 
+2

爲兩點之間的最小距離緯度/經度,它應該是sqrt((x1-x2)^ 2 +(y1-y2)^ 2)'。這仍然是考慮一架飛機,更具體地說,在球體上,應該是一些不同的公式。 – CoderBC

+0

欣賞答案!仍在最後確定,以確保一切正常。我確實需要更新dist函數,以便在緯度計算周圍有一個np.abs,然後再圍繞經度計算。有些時候,如果緯度偏離正值,經度偏離負值,他們就會抵消並給我一些甚至不那麼接近的東西。除此之外,我相信它完美地起作用。那麼我會將輸出合併到索引上的位置數據框? – sokeefe1014

+0

@ sokeefe1014將結果包含在原始數據幀中的最佳方式可能類似於'locations ['closest_station'] = locations.apply(lambda row:...,axis = 1)''。 – IanS

0

所以我明白這有點亂,但我用了類似的方法來匹配表格之間的基因數據。它依賴於位置文件的經度和緯度在天氣文件中的5個之內,但是如果需要的話可以改變它們。

rows=range(location.shape[0]) 
weath_rows = range(weather.shape[0]) 
for r in rows: 
    lat = location.iloc[r,1] 
    max_lat = lat +5 
    min_lat = lat -5 
    lon = location.iloc[r,2] 
    max_lon = lon +5 
    min_lon = lon -5 
    for w in weath_rows: 
     if (min_lat <= weather.iloc[w,2] <= max_lat) and (min_lon <= weather.iloc[w,3] <= max_lon): 
      location['Station_Name'] = weather.iloc[w,1] 
相關問題