来自网络x中DiGraph的邻接矩阵

时间:2017-05-12 20:35:31

标签: graph networkx

目前我似乎可以在networkx中提取有向图的邻接列表,但是不支持定向提取邻接矩阵。如何从networkx中的DiGraph中提取邻接矩阵?

1 个答案:

答案 0 :(得分:1)

nx.adjacency_matrix返回SciPy稀疏(邻接)矩阵。要获得密集(NumPy)矩阵,请将其称为todense方法:

import networkx as nx

G = nx.path_graph(4, create_using=nx.DiGraph())
m = nx.adjacency_matrix(G)
print(m)
#   (0, 1)  1
#   (1, 2)  1
#   (2, 3)  1

print(m.todense())
# [[0 1 0 0]
#  [0 0 1 0]
#  [0 0 0 1]
#  [0 0 0 0]]

或者,请致电nx.to_numpy_matrix

print(nx.to_numpy_matrix(G))
# [[ 0.  1.  0.  0.]
#  [ 0.  0.  1.  0.]
#  [ 0.  0.  0.  1.]
#  [ 0.  0.  0.  0.]]

要获得纯Python列表,请调用NumPy矩阵的tolist方法:

print(m.todense().tolist())
# [[0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [0, 0, 0, 0]]