summaryrefslogtreecommitdiff
path: root/networkx/relabel.py
diff options
context:
space:
mode:
authorJeffrey Finkelstein <jeffrey.finkelstein@gmail.com>2015-11-16 01:53:04 -0500
committerJeffrey Finkelstein <jeffrey.finkelstein@gmail.com>2016-03-22 19:25:05 -0400
commit1bad3dc5452b00fb0d072ed48f0b4bad14275d1c (patch)
treed4436d1a8d0fd3138d3921a75cbf4594b135c5cc /networkx/relabel.py
parent08f6f0062195c466d981a5d3a2342666397c5af1 (diff)
downloadnetworkx-1bad3dc5452b00fb0d072ed48f0b4bad14275d1c.tar.gz
Clarifies some examples for relabel_nodes().
Diffstat (limited to 'networkx/relabel.py')
-rw-r--r--networkx/relabel.py69
1 files changed, 43 insertions, 26 deletions
diff --git a/networkx/relabel.py b/networkx/relabel.py
index 7eb95a10..d1a95d7d 100644
--- a/networkx/relabel.py
+++ b/networkx/relabel.py
@@ -27,32 +27,49 @@ def relabel_nodes(G, mapping, copy=True):
Examples
--------
- >>> G=nx.path_graph(3) # nodes 0-1-2
- >>> mapping={0:'a',1:'b',2:'c'}
- >>> H=nx.relabel_nodes(G,mapping)
- >>> print(sorted(H.nodes()))
- ['a', 'b', 'c']
-
- >>> 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(),range(1,27)))
- >>> G1=nx.relabel_nodes(G,mapping) # nodes 1..26
-
- Partial in-place mapping:
-
- >>> G = nx.path_graph(3) # nodes 0-1-2
- >>> 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']
-
- Mapping as function:
-
- >>> G = nx.path_graph(3)
- >>> H = nx.relabel_nodes(G, lambda x: x ** 2)
- >>> list(H)
- [0, 1, 4]
+ 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 in-place 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 0-1-2
+ >>> 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
-----