1

I am trying to process the graph given in wiki-Vote.txt (https://snap.stanford.edu/data/wiki-Vote.html). There are 7115 nodes with id ranging from 3 to 8297. I want to relabel the nodes from 0 to 7114. I checked the mappings in relabel_nodes() but still could not solve the problem. Please suggest. thanks

Raj P Raj
  • 31
  • 1
  • 3
  • 1
    What _is_ the problem? How does it manifest? (What happened when you tried to check the mappings in `relabel_nodes()`?) What have you tried to do in response to that? If it's a home/coursework exercise, it'd be appreciated if you indicated it. – zyndor Oct 06 '17 at 13:33
  • the mappings seems to be either specified explicitly or defined for a contiguous range. how can the mapping be defined for my case? Its not a homework. thanks. – Raj P Raj Oct 06 '17 at 14:45
  • What have you tried? I'm not sure what you mean by: "I checked the mappings in relabel_nodes() but still could not solve the problem." – Joel Oct 06 '17 at 16:38
  • @Joel, Let a graph be 2--3, 5---7, 3---5. I want to change the labels to 0--1, 2--3, 1--2. How to define the mapping here. We can explicitly define it for this example. But how to do it for a large graph. – Raj P Raj Oct 07 '17 at 07:30

1 Answers1

7

edit I'm not sure if it's new, but my original answer didn't mention nx.convert_node_labels_to_integers(G, first_label=0, ordering='default', label_attribute=None). So for a given graph G, you can do H=nx.convert_node_labels_to_integers(G). This doesn't guarantee that the order is the same as in G. You can have the original label be stored in H if you call H=nx.convert_node_labels_to_integers(G, label_attribute='original_name'). You can guarantee that the order is the same as in G, by setting ordering=sorted(G.nodes()).

original answer

Given a graph G with some set of nodes, the simplest thing would be

mapping = {old_label:new_label for new_label, old_label in enumerate(G.nodes())}
H = nx.relabel_nodes(G, mapping)

This will create a dictionary mapping whose keys are the old labels and whose values are their new labels (read up on dictionary comprehensions). The ordering of the new labels is given by the order that G.nodes() returns the values (which you can't control). The new graph H has the node labels changed.

If you want a specific order, you need to sort G.nodes() appropriately. So you can do

nodelist = G.nodes()
nodelist.sort()
mapping = {old_label:new_label for new_label, old_label in enumerate(nodelist)}
H = nx.relabel_nodes(G, mapping)

which would have them sorted in numerical order (or alphabetical order if the node names are strings). If you want some other custom order, you'll have to figure out how to sort nodelist.

Joel
  • 22,598
  • 6
  • 69
  • 93