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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With