How to only keep nodes in networkx-graph with 2+ outgoing edges or 0 outgoing edges?

user494461 picture user494461 · Dec 20, 2011 · Viewed 9k times · Source

I have Directed Graph in networkx. I want to only keep those nodes which have two or more than two outgoing edges or no outgoing edge at all. How do I do this?

or

How do I removes nodes which have exactly one outgoing edge in a networkx graph.

Answer

Michael J. Barber picture Michael J. Barber · Dec 20, 2011

You can find the nodes in graph G with one outgoing edge using the out_degree method:

outdeg = G.out_degree()
to_remove = [n for n in outdeg if outdeg[n] == 1]

Removing is then:

G.remove_nodes_from(to_remove)

If you prefer to create a new graph instead of modifying the existing graph in place, create a subgraph:

to_keep = [n for n in outdeg if outdeg[n] != 1]
G.subgraph(to_keep)