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.
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)