11

I am attempting to create a random networkx graph with each edge having a random weight (representing length).

At the moment I am using the gnm_random_graph function from the set of networkx graph generators:

g=nx.gnm_random_graph(5,5)

However, I am struggling to add the random weights. My attempt is based on answers to this question.

for u,v,w in in g.edges(data=True):
     w = np.random.randint(0,10)

I am doing this so I can explore and (hopefully) understand the networkx library.

My question has two parts:

1. What is the best way generate a simple networkx graph for example purposes?

2. What is the best way to add weights to an existing networkx graph?

Community
  • 1
  • 1
atomh33ls
  • 23,172
  • 18
  • 91
  • 149

1 Answers1

8

Just addressing question 2 (Q1 is very dependent on context)

you could use (I believe in both networkx 1.x and 2.x):

import random
#code creating G here
for (u,v,w) in G.edges(data=True):
    w['weight'] = random.randint(0,10)

The variable w is a dictionary whose keys are all the different edge attributes.

Alternatively in networkx 2.x you can do

for (u, v) in G.edges():
    G.edges[u,v]['weight'] = random.randint(0,10)

or in networkx 1.x you can do

for (u, v) in G.edges():
    G.edge[u][v]['weight'] = random.randint(0,10)
Joel
  • 17,416
  • 3
  • 50
  • 81