I'm trying to take a weighted networkx graph and convert it to an edgelist .txt file, where each row takes the form of three space-delimited numbers that indicate the starting node, ending node, and corresponding weight.
Here's what I've tried for a simple seven-node, weighted undirected graph:
import networkx as nx
import numpy as np
A = np.matrix([[0,7,7,0,0],[7,0,6,0,0],[7,6,0,2,1],[0,0,2,0,4],
[0,0,1,4,0]])
G = nx.from_numpy_matrix(A)
nx.write_edgelist(G, "weighted_test_edgelist.txt", delimiter=' ')
The text file is created and looks as follows:
0 1 {'weight': 7}
0 2 {'weight': 7}
1 2 {'weight': 6}
2 3 {'weight': 2}
2 4 {'weight': 1}
3 4 {'weight': 4}
However, I want the above to instead appear as
0 1 7
0 2 7
1 2 6
2 3 2
2 4 1
3 4 4
Try:
nx.write_edgelist(G, "weighted_test_edgelist.txt", delimiter=' ', data=['weight'])
Output:
0 1 7
0 2 7
1 2 6
2 3 2
2 4 1
3 4 4
Per docs:
data : bool or list, optional If False write no edge data. If True write a string representation of the edge data dictionary.. If a list (or other iterable) is provided, write the keys specified
in the list.