18

I am using the NetworkX graph library for Python. At some point in my program I would like to "consolidate" my nodeIDs into a sequence of numbers. Here's my naive approach:

start = 1 # could be anything
for i, n in enumerate(g.nodes()):
    if i+start == n:
        continue
    g.add_node(i+start, attr_dict=g.node[n])
    g.add_edges_from([(i+start, v, g[n][v]) for v in g.neighbors(n)])
    g.remove_node(n)

Is there a faster way than this exhaustive copy of all the neighbors? For example, I tried g[i+start] = g[n], but that is forbidden.

Thanks!

2 Answers 2

11

Would this work?

http://networkx.github.io/documentation/latest/reference/generated/networkx.relabel.convert_node_labels_to_integers.html

import networkx as nx
G = nx.Graph()
G.add_node(1)
G.add_nodes_from('spam')
print G.nodes()

returns:

['a', 1, 's', 'm', 'p']

now:

start = 1
G = nx.convert_node_labels_to_integers(G,first_label=start)
print G.nodes()

returns:

[1, 2, 3, 4, 5]
2
  • Thanks Josh! That function does exactly what I asked. But unfortunately it's not in-place, so looking at the source (lines 214-357) it's still O(V+E) instead of the theoretically-possible O(V). Still, it looks like it's 25% faster than my attempt.
    – Juan
    Mar 17, 2011 at 1:03
  • 1
    It just occurred to me that given the way graphs are implemented in networkx, the O(V) bound won't be attainable. Every edge will have to be visited to remap the nodeID.
    – Juan
    Mar 17, 2011 at 1:53
10

In case your interest is still relevant, there is networkx.relabel_nodes() which takes a mapping dictionary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.