python-igraph how to add edges with weight?
I have a tuple list like [('1', '177', 1.0), ('1', '54', 1.0), ('1', '61', 2.0), ('1', '86', 2.0), ('10', '100', 38.0)]
. The last one in the tuple is the weight of edge from '1'
to '177'
.
But how to add it? I use
g.add_vertices(vertexList)
g.add_edges(edgelist)
but it is wrong.
We need to do some pre-processing first.
The following code works fine and does what you asked.
from igraph import *
# Here we have 5 edges
a = [('1', '177', 1.0), ('1', '54', 1.0), ('1', '61', 2.0),
('1', '86', 2.0), ('10', '100', 38.0)]
edge = []
weights = []
# the loop for i is in range(5) because you have 5 edges
for i in range(5):
for j in range(2):
k =2
edge.append(a[i][j])
weights.append(a[i][k])
edges = [(i,j) for i,j in zip(edge[::2], edge[1::2])]
list1 = []
for i in range(len(edges)):
list1.append((int(edges[i][0]), int(edges[i][1])))
g= Graph()
g.add_vertices(178)
g.add_edges(list1)
g.es['weight'] = weights
g.ecount()
5
g.es['weight']
[1.0, 1.0, 2.0, 2.0, 38.0]
You have not longer "preprocess" data, becouse this format is accurate for new method:
g = Graph.TupleList([(from, to, weight], ...)
one more example from author:
g=Graph.TupleList([("a", "b", 3.0), ("c", "d", 4.0), ("a", "c", 5.0)], weights=True)
Method is available from version 0.6.1, what said author here: https://answers.launchpad.net/igraph/+question/206397
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