user2954167
user2954167

Reputation: 154

How to find a directed path in NetworkX?

So. I'm trying to find paths through a directed graph.

I start out with a Pandas data frame with 3 columns: 'Source', 'Target', 'weight.' The weight is used to keep track of the action of each target (it's just a number).

Then I convert the df into an edge list:

edge_list = nx.from_pandas_edgelist(df, 'Source','Target','weight')

Then for good measure, I convert this into a directed graph (and I'm fairly confident this is happening correctly)

directed_graph = nx.DiGraph(edge_list)

However, whenever I start to search for paths within the graphs, I'm getting undirected paths. I checked and double-checked but if I define a path

path = nx.shortest_path(directed_graph,source=A,target=B,weight='weight')

the path that's returned can't be found by following the directed paths found in the graph. (It can, however be found by following undirected paths, so I guess that's something)

Upvotes: 1

Views: 1427

Answers (1)

abc
abc

Reputation: 11929

You can direclty create your digraph by specifying create_using=nx.DiGraph()

g = nx.from_pandas_edgelist(df, 'Source','Target','weight', create_using=nx.DiGraph())

nx.from_pandas_edgelist returns an instance of a graph, not an edge list, so you are first creating a graph and then converting it to a digraph by adding two directed arcs (i,j), (j,i) for each undirected edge (i,j).

Example:

>>> g=nx.from_edgelist([(1,2),(3,4)])
>>> g.edges()
EdgeView([(1, 2), (3, 4)])
>>> nx.DiGraph(g).edges()
OutEdgeView([(1, 2), (2, 1), (3, 4), (4, 3)])

Upvotes: 2

Related Questions