How to replace a node name with a new one?

3,364 views
Skip to first unread message

Timmy

unread,
May 12, 2009, 11:40:00 PM5/12/09
to networkx...@googlegroups.com
Hi,
I'm new to networkx. Is there any convenient function to
replace an existing node name from a graph. To do so because I want to use the compose function to compose two
graph into one. It needs to have a common node name to successfully do it.
Although I can write code by myself, if there is a function already available in current networkx, I need not
to write this function.

Thanks!

Dan Schult

unread,
May 13, 2009, 8:35:58 AM5/13/09
to networkx...@googlegroups.com
Try the function relabel_nodes()

Looks like it is not on the documentation webpages.
I'll try to get that fixed.

Here's the docstring:

Return a copy of G with node labels transformed by mapping.

Parameters
----------
G : graph
A NetworkX graph

mapping : dictionary or function
Either a dictionary with the old labels as keys and new labels
as values
or a function transforming an old label with a new label
In either case, the new labels must be hashable Python objects.

Examples
--------
mapping as dictionary

>>> G=nx.path_graph(3) # nodes 0-1-2
>>> mapping={0:'a',1:'b',2:'c'}
>>> H=nx.relabel_nodes(G,mapping)
>>> print H.nodes()
['a', 'c', 'b']

>>> G=nx.path_graph(26) # nodes 0..25
>>> mapping=dict(zip(G.nodes(),"abcdefghijklmnopqrstuvwxyz"))
>>> H=nx.relabel_nodes(G,mapping) # nodes a..z
>>> mapping=dict(zip(G.nodes(),xrange(1,27)))
>>> G1=nx.relabel_nodes(G,mapping) # nodes 1..26

mapping as function

>>> G=nx.path_graph(3)
>>> def mapping(x):
... return x**2
>>> H=nx.relabel_nodes(G,mapping)
>>> print H.nodes()
[0, 1, 4]

Also See
--------
convert_node_labels_to_integers()
Reply all
Reply to author
Forward
0 new messages