目前我似乎可以在networkx中提取有向图的邻接列表,但是不支持定向提取邻接矩阵。如何从networkx中的DiGraph中提取邻接矩阵?
答案 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]]