使用python networkx的节点之间的距离

时间:2014-10-11 08:45:30

标签: python-3.x graph nodes networkx euclidean-distance

我是NetworkX的新手,我需要找到两个节点之间的距离。我已经试了一下,但大多数搜索都会导致DFSDijkstra等方法,这不是我的观点。我只想要两组坐标之间的欧几里德距离,后者代表图中的节点。

1 个答案:

答案 0 :(得分:0)

正如上面的评论所指出的,你可以很容易地做到这一点。您需要做的就是在for loop内实现Euclidean distance formula,迭代图中的所有节点。从技术上讲,下面的代码段集中在edges,但它们的长度正是您所寻找的:节点A和节点B之间的距离(起点和终点)。

如果您需要进行进一步的分析,例如计算边长分布,则可以将结果保存在dictionary中。

import networkx as nx
import math

#Create a test graph
m=2  #Number of initial links
n=100 #Number of nodes
ncols=10 #Number of columns in a 10x10 grid of positions
G=nx.barabasi_albert_graph(n, m, j)
pos = {i : (i // ncols, (n-i-1) % ncols) for i in G.nodes()}

#Compute the node-to-node distances
lengths={}
for edge in G.edges():
   startnode=edge[0] 
   endnode=edge[1]
   lengths[edge]=round(math.sqrt(((pos[endnode][1]-pos[startnode][1])**2)+
                                      ((pos[endnode][0]-pos[startnode][0])**2)),2) #The distance

如果您想计算边长分布,可以使用:

import pandas as pd

items=sorted(lengths.items())
values=lengths.values()
df = pd.DataFrame({'Lengths':values})

df['Lengths'].hist(df, bins=10) #Change to as many bins as you want/need