I have a graph in NetworkX that roughly is like this:
a---b---c---d
|
e---f
I want to simplify it, removing intermediary nodes that have only 2 edges.
a---b---d
|
f
How can this be done in NetworkX? I only see remove node methods, or contract edges. But this has to do with nodes instead.
It can be done as follows:
for node in list(G.nodes()):
if G.degree(node) == 2:
edges = list(G.edges(node))
G.add_edge(edges[0][1], edges[1][1])
G.remove_node(node)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With