'nx.read_edgelist read the data wrong from a .txt file

I have the following data in a edges.txt file:

# node1 node2 weight
1 2 3
1 3 2
2 4 16
2 9 17
3 5 7
3 6 1
4 6 11
4 8 4
4 9 8
5 6 6
5 7 15
6 7 5
6 8 10
7 8 12
7 10 13
8 9 18
8 10 9
9 10 14

I want to create s simple G = nx.Graph() using the following code:

import networkx as nx
target_path = open('./edges.txt', 'r')
G = nx.read_edgelist(target_path, create_using=nx.Graph, nodetype=int, data=(("weight", int),))
G.nodes
list_edges = list(G.edges(data=True))

The outputs are:

NodeView((1, 2, 3, 4, 9, 5, 6, 8, 7, 10))
[(1, 2, {'weight': 3}),
 (1, 3, {'weight': 2}),
 (2, 4, {'weight': 16}),
 (2, 9, {'weight': 17}),
 (3, 5, {'weight': 7}),
 (3, 6, {'weight': 1}),
 (4, 6, {'weight': 11}),
 (4, 8, {'weight': 4}),
 (4, 9, {'weight': 8}),
 (9, 8, {'weight': 18}),
 (9, 10, {'weight': 14}),
 (5, 6, {'weight': 6}),
 (5, 7, {'weight': 15}),
 (6, 7, {'weight': 5}),
 (6, 8, {'weight': 10}),
 (8, 7, {'weight': 12}),
 (8, 10, {'weight': 9}),
 (7, 10, {'weight': 13})]

As you can see my .py file read

(9, 8, {'weight': 18})

(8, 7, {'weight': 12}),

Instead of the right (8, 9, {'weight': 18}) and (7, 8, {'weight': 12}) as stated in the input .txt file.

I've tried using .cvs and .xlsx files and it is the same. I'm using macOS (M1 processor) Anaconda (Spyder IDE). I am building the .txt file using mac TextEdit plain text.

Any help will be highly appreciated.



Solution 1:[1]

Your graph is undirected, so an A-B edge is the same as B-A.

If you use a directed graph, you will get the correct direction:

G = nx.read_edgelist(target_path, create_using=nx.DiGraph,
                     nodetype=int, data=(("weight", int),))

edges:

[(1, 2, {'weight': 3}),
 (1, 3, {'weight': 2}),
 (2, 4, {'weight': 16}),
 (2, 9, {'weight': 17}),
 (3, 5, {'weight': 7}),
 (3, 6, {'weight': 1}),
 (4, 6, {'weight': 11}),
 (4, 8, {'weight': 4}),
 (4, 9, {'weight': 8}),
 (9, 10, {'weight': 14}),
 (5, 6, {'weight': 6}),
 (5, 7, {'weight': 15}),
 (6, 7, {'weight': 5}),
 (6, 8, {'weight': 10}),
 (8, 9, {'weight': 18}),
 (8, 10, {'weight': 9}),
 (7, 8, {'weight': 12}),
 (7, 10, {'weight': 13})]

directed graph:

graph

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mozway