我會給一個純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
你有任何代碼了嗎?請至少提供一段代碼,讓您將這些距離讀入內存以獲得類似於線纜的內容[boston] =(5,2) – pkacprzak
現在即時閱讀CSV文件,如下所示:Data = pd.read_csv('C:\ Users \傑裏\桌面\ cities.csv') – Jeremy