Search code examples
graphnetworkx

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


I have a list of networkX graphs gSet that are of varying sizes. I want to add isolated nodes to all of them such that they all have the same number of nodes thereby padding their adjacency matrices on the right and bottom with 0's. This is what I have tried thus far, maxNodes is the number of nodes in the largest graph from the list:

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) 

This doesn't seem to change all the graphs to be the same size however.


Solution

  • # 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))