尝试用 0 填充 networkx 图的邻接矩阵

Trying to pad adjacency matrix of networkx graph with 0's

我有一个不同大小的 networkX 图列表 gSet。我想向所有这些节点添加孤立节点,以便它们都具有相同数量的节点,从而在右侧和底部用 0 填充它们的邻接矩阵。这是我迄今为止尝试过的方法,maxNodes 是列表中最大图中的节点数:

for i in range(0, len( gSet )):

     numOfNodes = nx.to_numpy_array( gSet[i] ).shape[0] 

     for j in range(maxNodes - numOfNodes, maxNodes ):

         gSet[i].add_node(j) 

然而,这似乎并没有将所有图表更改为相同大小。

gSet.add_node(j) 

这看起来不正确。您想要将额外的节点添加到 gSet 中的一个图形中。

# collection of dummy graphs:
gSet = []
for _ in range(10):
    size = np.random.randint(1,8)
    G = nx.from_numpy_array(np.random.rand(size,size)>0.8)
    gSet.append(G)

# check number of nodes in each graph:
print('before:')
for g in gSet:
    print(len(g))
    
# find number of nodes in graph with most nodes:
max_nodes = max([len(g) for g in gSet])

# networkx numbers nodes from 0 to the number of nodes -1 (=length of the graph -1)
# so len(g) gives the smallest positive integer that can be used as a node name.
for g in gSet:
    while len(g) < max_nodes:
        g.add_node(len(g))
        
# check number of nodes in each graph:
print('after:')
for g in gSet:
    print(len(g))