2015-04-06 142 views
3

我目前正在將數據讀入一個看起來像這樣的數據框。創建距離矩陣?

City   XCord YCord 
Boston   5  2 
Phoenix  7  3 
New York  8  1 
.....   .  . 

我想從這個數據顯示,所有城市對之間的距離,建立歐氏距離矩陣,所以我得到一個結果矩陣,如:

   Boston Phoenix New York 
Boston   0  2.236  3.162 
Phoenix  2.236  0  2.236 
New York  3.162 2.236  0 

還有更多的城市和座標我實際的數據框架,所以我需要能夠以某種方式迭代所有的城市對,並創建一個距離矩陣,就像我上面顯示的距離矩陣,但是我不知道如何將所有的邊距組合在一起,並應用歐幾里得距離公式?任何幫助,將不勝感激。

+0

你有任何代碼了嗎?請至少提供一段代碼,讓您將這些距離讀入內存以獲得類似於線纜的內容[boston] =(5,2) – pkacprzak

+0

現在即時閱讀CSV文件,如下所示:Data = pd.read_csv('C:\ Users \傑裏\桌面\ cities.csv') – Jeremy

回答

6

我認爲你對distance_matrix感興趣。

例如:

創建數據:

import pandas as pd 
from scipy.spatial import distance_matrix 

data = [[5, 7], [7, 3], [8, 1]] 
ctys = ['Boston', 'Phoenix', 'New York'] 
df = pd.DataFrame(data, columns=['xcord', 'ycord'], index=ctys) 

輸出:

  xcord ycord 
Boston  5 7 
Phoenix  7 3 
New York 8 1 

使用距離矩陣函數:

pd.DataFrame(distance_matrix(df.values, df.values), index=df.index, columns=df.index) 

結果:

  Boston Phoenix  New York 
Boston 0.000000 4.472136 6.708204 
Phoenix 4.472136 0.000000 2.236068 
New York 6.708204 2.236068 0.000000 
0

我會給一個純python的方法。

導入從數學模塊sqrt函數:

from math import sqrt

我們假設你以下面的方式有你的座標線表:

cords['Boston'] = (5, 2)

定義一個函數來計算兩個給定2d點的歐幾里德距離:

def dist(a, b): 
    d = [a[0] - b[0], a[1] - b[1]] 
    return sqrt(d[0] * d[0] + d[1] * d[1]) 

初始化所得矩陣作爲字典:

D = {} 

for city1, cords1 in cords.items(): 
    D[city1] = {} 
    for city2, cords2 in cords.items(): 
     D[city1][city2] = dist(cords1, cords2) 

d是你的結果矩陣

完整的源是下面具有印刷結果一起:

from math import sqrt 

cords = {} 
cords['Boston'] = (5, 2) 
cords['Phoenix'] = (7, 3) 
cords['New York'] = (8, 1) 

def dist(a, b): 
    d = [a[0] - b[0], a[1] - b[1]] 
    return sqrt(d[0] * d[0] + d[1] * d[1]) 

D = {} 

for city1, cords1 in cords.items(): 
    D[city1] = {} 
    for city2, cords2 in cords.items(): 
     D[city1][city2] = dist(cords1, cords2) 

for city1, v in D.items(): 
    for city2, d in v.items(): 
     print city1, city2, d 

結果:

Boston Boston 0.0 
Boston New York 3.16227766017 
Boston Phoenix 2.2360679775 
New York Boston 3.16227766017 
New York New York 0.0 
New York Phoenix 2.2360679775 
Phoenix Boston 2.2360679775 
Phoenix New York 2.2360679775 
Phoenix Phoenix 0.0 
0

scip中有這個功能Y: scipy.spatial.distance.cdist()

1

,如果你不希望使用SciPy的,你可以用這種方式利用列表理解:

dist = lambda p1, p2: sqrt(((p1-p2)**2).sum()) 
dm = np.asarray([[dist(p1, p2) for p2 in xy_list] for p1 in xy_list])