Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to contract nodes that have only 2 edges in NetworkX?

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.

like image 242
culebrón Avatar asked Feb 04 '26 11:02

culebrón


1 Answers

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)
like image 136
zohar.kom Avatar answered Feb 06 '26 03:02

zohar.kom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!