Truong Hoang
Truong Hoang

Reputation: 332

How to `read_edgelist` of networkx set default custom weight?

I'm using networkx to read edges from file. My data likes:

1 2
1 3
2 4

How to set custom weight when read from above data? I want to my data likes:

1 2 1.0
1 3 1.0
2 4 1.0

or weight may be other value which can be chose without weight in original data.

Upvotes: 1

Views: 289

Answers (1)

yatu
yatu

Reputation: 88236

You could build a weighted edge list while reading the file into a nested list, and then feed the weighted edges into a graph with add_weighted_edges_from:

weight = 1
edges = [[*map(int,line.split()), weight] for line in open("file.txt")]
G = nx.Graph()
G.add_weighted_edges_from(edges)
G.edges(data=True)
# EdgeDataView([(1, 2, {'weight': 1}), (1, 3, {'weight': 1}), (2, 4, {'weight': 1})])

Upvotes: 1

Related Questions