networkx.relabel.relabel_nodes¶

relabel_nodes
(G, mapping, copy=True)[source]¶ Relabel the nodes of the graph G.
Parameters:  G (graph) – A NetworkX graph
 mapping (dictionary) – A dictionary with the old labels as keys and new labels as values. A partial mapping is allowed.
 copy (bool (optional, default=True)) – If True return a copy, or if False relabel the nodes in place.
Examples
To create a new graph with nodes relabeled according to a given dictionary:
>>> G = nx.path_graph(3) >>> sorted(G) [0, 1, 2] >>> mapping = {0: 'a', 1: 'b', 2: 'c'} >>> H = nx.relabel_nodes(G, mapping) >>> sorted(H) ['a', 'b', 'c']
Nodes can be relabeled with any hashable object, including numbers and strings:
>>> import string >>> G = nx.path_graph(26) # nodes are integers 0 through 25 >>> sorted(G)[:3] [0, 1, 2] >>> mapping = dict(zip(G, string.ascii_lowercase)) >>> G = nx.relabel_nodes(G, mapping) # nodes are characters a through z >>> sorted(G)[:3] ['a', 'b', 'c'] >>> mapping = dict(zip(G, range(1, 27))) >>> G = nx.relabel_nodes(G, mapping) # nodes are integers 1 through 26 >>> sorted(G)[:3] [1, 2, 3]
To perform a partial inplace relabeling, provide a dictionary mapping only a subset of the nodes, and set the
copy
keyword argument to False:>>> G = nx.path_graph(3) # nodes 012 >>> mapping = {0: 'a', 1: 'b'} # 0>'a' and 1>'b' >>> G = nx.relabel_nodes(G, mapping, copy=False) >>> sorted(G, key=str) [2, 'a', 'b']
A mapping can also be given as a function:
>>> G = nx.path_graph(3) >>> H = nx.relabel_nodes(G, lambda x: x ** 2) >>> list(H) [0, 1, 4]
Notes
Only the nodes specified in the mapping will be relabeled.
The keyword setting copy=False modifies the graph in place. Relabel_nodes avoids naming collisions by building a directed graph from
mapping
which specifies the order of relabelings. Naming collisions, such as a>b, b>c, are ordered such that “b” gets renamed to “c” before “a” gets renamed “b”. In cases of circular mappings (e.g. a>b, b>a), modifying the graph is not possible inplace and an exception is raised. In that case, use copy=True.See also