0
看來,目前我可以在networkx中提取有向圖的鄰接列表,但是它不支持定向提取鄰接矩陣。如何從networkx中的DiGraph提取鄰接矩陣?DiGraph在網絡中的鄰接矩陣x
看來,目前我可以在networkx中提取有向圖的鄰接列表,但是它不支持定向提取鄰接矩陣。如何從networkx中的DiGraph提取鄰接矩陣?DiGraph在網絡中的鄰接矩陣x
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]]