13
votes

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.

1
If you start with a graph, find the nodes which have one outgoing edge, and then remove those, you can create a new graph which still has a node with one outgoing edge (say it had two before and one of the involved nodes was removed.) What would you like to do in that case? - DSM

1 Answers

24
votes

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)