Search code examples
pythonpython-3.xnetworkx

networkx.relabel.convert_node_labels_to_integers explanation


I have a simple graph like the one below:

    edge_list = [[1,1],[1,2],[1,3],[2,3]]

I want to use the relabel.convert_node_labels_to_integers() method to label the nodes with consecutive integers like it says in the documentation. What was I expecting from the use of the method is the following dict:

    {0: 0, 1: 1, 2: 2, 3:3}

But I am getting the following:

    {0: 0, 1: 1, 2: 2}

Could someone explain to me why? Thanks


Solution

  • The edge list defines three nodes, 1,2,3 (with four edges among them).

    import networkx as nx
    
    G = nx.Graph()
    
    edge_list = [[1, 1], [1, 2], [1, 3], [2, 3]]
    
    G.add_edges_from(edge_list)
    
    print(G.nodes())  # [1, 2, 3]
    
    GG = nx.relabel.convert_node_labels_to_integers(G)
    
    print(GG.nodes())  # [0, 1, 2]
    
    mapping = {k: GG.nodes[k]["old_id"] for k in GG.nodes()}
    print(mapping) # {0: 1, 1: 2, 2: 3}
    

    In your output, it seems that at some point the nodes were (re)named using 0,1,2. In that case, renaming node labels then has no effect, so dictionary keys and values match.