8. Directed graphs
The DiGraph
(opens new window) class provides additional properties specific to directed edges, e.g., DiGraph.out_edges()
(opens new window), DiGraph.in_degree()
(opens new window), DiGraph.predecessors()
(opens new window), DiGraph.successors()
(opens new window) etc. To allow algorithms to work with both classes easily, the directed versions of neighbors()
is equivalent to successors()
while degree
reports the sum of in_degree
and out_degree
even though that may feel inconsistent at times.
DG = nx.DiGraph()
DG.add_weighted_edges_from([(1, 2, 0.5), (3, 1, 0.75)])
DG.out_degree(1, weight='weight')
DG.degree(1, weight='weight')
list(DG.successors(1))
list(DG.neighbors(1))
2
3
4
5
6
7
8
9
Some algorithms work only for directed graphs and others are not well defined for directed graphs. Indeed the tendency to lump directed and undirected graphs together is dangerous. If you want to treat a directed graph as undirected for some measurement you should probably convert it using Graph.to_undirected()
(opens new window) or with
H = nx.Graph(G) # convert G to undirected graph