Suman Pandey
Suman Pandey

Reputation: 21

How to assign/attach weight in edges of graph?

I want to attach same or different weight with bunch of edges. But i do not find any function for this in NetworkX. If function is available in Networkx then what is it ,if not then suggest me how to attach weight with edges in python? For examle: If i have some edge list ,which has no edges

edges=[(1,2),(1,4),(3,4),(4,2)]

then i want to attach same weight (1) with all edges.

expected output is : weighted_edges=[(1,2,1),(1,4,1),(3,4,1),(4,2,1)]

Upvotes: 0

Views: 4522

Answers (2)

Joel
Joel

Reputation: 23907

The simplest version is to use add_weighted_edges_from

import networkx as nx
G=nx.Graph()
G.add_weighted_edges_from([(1,2,1),(1,4,1),(3,4,1),(4,2,1)])
G.edges(data=True)  #print out the edges with weight
>[(1, 2, {'weight': 1}),
 (1, 4, {'weight': 1}),
 (2, 4, {'weight': 1}),
 (3, 4, {'weight': 1})]

If you've already defined edges, then create the edges with their weights:

edges=[(1,2),(1,4),(3,4),(4,2)]
edges_with_weights=[(a,b,1) for (a,b) in edges]
H=nx.Graph()
H.add_weighted_edges_from(edges_with_weights)
H.edges(data=True)
> [(1, 2, {'weight': 1}),
(1, 4, {'weight': 1}),
(2, 4, {'weight': 1}),
(3, 4, {'weight': 1})]

Upvotes: 4

Alex
Alex

Reputation: 19124

See networkx's tutorial.

import networkx as nx
G = nx.Graph()
G.add_nodes_from([1, 2, 3, 4, 5])

G.add_edge(1, 2, weight=4.7 )
G.add_edges_from([(1,2), (2,3,{'weight':8})])
G[1][2]['weight'] = 4.7
G.edge[1][2]['weight'] = 4

In your example

G.add_edges_from(edges, weight=1)

Adds all the edges with a default weight of 1.

Upvotes: 1

Related Questions