如何计算邻接矩阵csv [python]的短路径测地距离?

how to calculate short path geodesic distance of adjacency matrix csv [python]?

我有一个图的邻接矩阵

graph

n 1 2 3 4 5 6 7 8 9

1 0 1 1 1 0 0 0 0 0

2 1 0 1 0 0 0 0 0 0

3 1 1 0 1 0 0 0 0 0

4 1 0 1 0 1 1 0 0 0

5 0 0 0 1 0 1 1 1 0

6 0 0 0 1 1 0 1 1 0

7 0 0 0 0 1 1 0 1 1

8 0 0 0 0 1 1 1 0 0

9 0 0 0 0 0 0 1 0 0

如何使用python将其转换为测地距离矩阵?

我的目标是让它变成这样:

n 1 2 3 4 5 6 7 8 9

1 0 1 1 1 2 2 3 3 4

2 1 0 1 2 3 3 4 4 5

3 1 1 0 1 2 2 3 3 4

4 1 2 1 0 1 1 2 2 3

5 2 3 2 1 0 1 1 1 2

6 2 3 2 1 1 0 1 1 2

7 3 4 3 2 1 1 0 1 1

8 3 4 3 2 1 1 1 0 2

9 4 5 4 3 2 2 1 2 0

我已经在 networkx 中尝试了一些代码,但它只能在 (n) 的一个来源和一个目的地计算,而不是整个矩阵。我真的需要你的帮助。 谢谢

networkx可以计算整个矩阵。只需不需要将源或目标提供给 nx.shortest_path 函数(参见 https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.algorithms.shortest_paths.generic.shortest_path.html - 最后一个示例)。这是我的解决方案:

import pprint
import networkx as nx
import pandas as pd
import numpy as np
mat = pd.read_csv('adjacency.csv', index_col=0, delim_whitespace=True).values
G = nx.from_numpy_matrix(mat)
p = nx.shortest_path(G)
shortest_path_mat = np.zeros(mat.shape)
for i in range(mat.shape[0]):
    shortest_path_mat[i, :] = np.array([len(x) for x in p[i].values()])
pprint.pprint(shortest_path_mat-1)

adjacency.csv

n 1 2 3 4 5 6 7 8 9

1 0 1 1 1 0 0 0 0 0

2 1 0 1 0 0 0 0 0 0

3 1 1 0 1 0 0 0 0 0

4 1 0 1 0 1 1 0 0 0

5 0 0 0 1 0 1 1 1 0

6 0 0 0 1 1 0 1 1 0

7 0 0 0 0 1 1 0 1 1

8 0 0 0 0 1 1 1 0 0

9 0 0 0 0 0 0 1 0 0