Skip to content
Advertisement

NetworkX: How to find the source and target nodes of a directed edge

dito above.. I couldn’t find anything in the NetworkX docs…

In Python Igraph, i can just use:

import igraph as ig
G = ig.Graph(directed=True)
G.add_vertices(2)
G.add_edge(0,1)
eid = G.get_eid(0,1)
edge = G.es[eid]
nodes = (edge.source, edge.target)
print nodes

Advertisement

Answer

Event though I came too late I want to contribute with my proposal, since I was looking for the same answer:

I am also looking for a command in the networkx package to find the “sources” and the “targets” of a Directed graph. But “sources” and “targets” of a Directed graph within the frame of Graph Theory are not simply the sources and targets of each edge as replied in this thread, but the equivalent of leaves for an undirected Graph. That is, source and target nodes whose degree is 1 (in different direction, of course).

I’d propose the following code:

import networkx as nx
G = nx.DiGraph()  # initializes a directed graph
edges = [(1,2),(2,3),(3,5),(4,5),(5,6)]
G.add_edges_from(edges)  # adds the edges to the graph G
sources = [x for x in G.nodes() if G.out_degree(x)==1 and G.in_degree(x)==0]
targets = [x for x in G.nodes() if G.out_degree(x)==0 and G.in_degree(x)==1]
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement