e.g. I have one graph with 3 nodes: a,b,c and 2 edges (a,b), (b,c). Now I'd like remove node b and merge edges (a,b),(b,c) into one edge (a,c), is there any api in networkx for this kind of graph manipulation? Thanks
You can use networkx.contracted_nodes
to generate a new graph with b
merged into a
:
G = nx.from_edgelist([('a', 'b'), ('b', 'c')])
H = nx.contracted_nodes(G, 'a', 'b', self_loops=False)
Or using contracted_edge
:
H = nx.contracted_edge(G, ('a', 'b'), self_loops=False)
NB. this returns a new graph, if you want to update in place, use copy=False
.
Before:
After: