我正在處理一個看起來像這樣的資料框:
lat lon
id_zone
0 40.0795 4.338600
1 45.9990 4.829600
2 45.2729 2.882000
3 45.7336 4.850478
4 45.6981 5.043200
我正在嘗試制作一個 Haverisne 距離矩陣。基本上對于每個區域,我想計算它與資料框中所有其他區域之間的距離。所以對角線上應該只有 0。這是我使用的 Haversine 函式,但我無法制作矩陣。
def haversine(x):
x.lon, x.lat, x.lon2, x.lat2 = map(radians, [x.lon, x.lat, x.lon2, x.lat2])
# formule de Haversine
dlon = x.lon2 - x.lon
dlat = x.lat2 - x.lat
a = sin(dlat / 2) ** 2 cos(x.lat) * cos(x.lat2) * sin(dlon / 2) ** 2
c = 2 * atan2(sqrt(a), sqrt(1 - a))
km = 6367 * c
return km
uj5u.com熱心網友回復:
您可以使用此答案Pandas - Creating Difference Matrix from Data Frame的解決方案
或者在您的特定情況下,您有一個像下面這樣的 DataFrame:
lat lon
id_zone
0 40.0795 4.338600
1 45.9990 4.829600
2 45.2729 2.882000
3 45.7336 4.850478
4 45.6981 5.043200
您的功能定義為:
def haversine(first, second):
# convert decimal degrees to radians
lat, lon, lat2, lon2 = map(np.radians, [first[0], first[1], second[0], second[1]])
# haversine formula
dlon = lon2 - lon
dlat = lat2 - lat
a = np.sin(dlat/2)**2 np.cos(lat) * np.cos(lat2) * np.sin(dlon/2)**2
c = 2 * np.arcsin(np.sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
return c * r
您經過的位置和位置的lat位置。lonfirstsecond
然后,您可以使用 Numpy 創建一個距離矩陣,然后用 hasrsine 函式的距離結果替換零:
# create a matrix for the distances between each pair of zones
distances = np.zeros((len(df), len(df)))
for i in range(len(df)):
for j in range(len(df)):
distances[i, j] = haversine(df.iloc[i], df.iloc[j])
pd.DataFrame(distances, index=df.index, columns=df.index)
您的輸出應與此類似:
id_zone 0 1 2 3 4
id_zone
0 0.000000 659.422944 589.599339 630.083979 627.383858
1 659.422944 0.000000 171.597296 29.555376 37.325316
2 589.599339 171.597296 0.000000 161.731366 174.983855
3 630.083979 29.555376 161.731366 0.000000 15.474533
4 627.383858 37.325316 174.983855 15.474533 0.000000
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/454561.html
上一篇:zip_longest過濾資料幀并輸出多個csv檔案
下一篇:如何同時向前和向后做熊貓滾動視窗
