J. van Leeuwen
J. van Leeuwen

Reputation: 87

How to stop Networkx from changing the order of edges when adding them from a list?

Adding edges from a list to a graph in NetworkX (python) changes the order of the edges, which causes problems for me when drawing the Graph. As example:

import networkx as nx

airports = ['A','B','C']
edgelst  = [['C','B'],['A','B'],['A','C']]

G = nx.Graph()

G.add_nodes_from(airports)
G.add_edges_from(edgelst)

This is the result if I check for the existing edges in the network:

>>> G.edges()
[('A', 'C'), ('A', 'B'), ('C', 'B')]

NetworkX has sorted the edges alphabetically, but I just want them to be in the same order as edgelst. How could I accomplish this?

Upvotes: 6

Views: 3330

Answers (2)

OpenCoderX
OpenCoderX

Reputation: 6318

If you use a traversal algorithm you can get the edges in the order they were visited in the path

```

paths = nx.all_simple_paths(G, source=0, target=3) for path in map(nx.utils.pairwise, paths): ... print(list(path)) [(0, 1), (1, 2), (2, 3)] [(0, 1), (1, 3)] [(0, 2), (2, 1), (1, 3)] [(0, 2), (2, 3)] [(0, 3)] ```

Upvotes: 0

harryscholes
harryscholes

Reputation: 1667

The answer to your question is a bit messy because the NetworkX Graph class doesn't retain the order of nodes in an edge. However, this can be circumvented by sorting each edge to guarantee node order. G.edges() can also be sorted by a custom key that retrieves the index that each edge appears in the edge list.

import networkx as nx

edgelist  = [['C','B'],['A','B'],['A','C']]

First, sort the nodes in each edge and create a dictionary that maps each edge to its index in the edge list:

edgelist = [sorted(edge) for edge in edgelist]
mapping = {tuple(edge): index for (edge, index) in zip(edgelist, range(len(edgelist)))}

Then sort the order of the graph's edges according to the index edges in the edge list:

G = nx.Graph()
G.add_edges_from(edgelist)
sorted(G.edges(), key=lambda edge: mapping[tuple(sorted(list(edge)))])

Upvotes: 3

Related Questions