Anna Yashina
Anna Yashina

Reputation: 534

Can not add edges to an empty graph

I try to create an empty graph and add some edges which I retrieve from a data frame like this:

edgelist = []
for i in range(len(edges)):
    edge = (int(edges.loc[i, 'source']), int(edges.loc[i, 'target']))
    if edge not in edgelist:
        edgelist.append(edge)

The edge list looks okay

[(0, 1), (0, 2), (1, 2), (0, 3), (2, 3), (2, 4), (3, 4)]

Then I create an empty graph and try to add edges:

G = ig.Graph()
G.add_edges(edgelist)

And it throws an error

Error at type_indexededgelist.c:272: cannot add edges, Invalid vertex id

What can be wrong with vertex id? I've tried to make ids start from 1 but it throws this error again.

Upvotes: 0

Views: 355

Answers (1)

ponylama
ponylama

Reputation: 51

You need to add vertics before you connect them with edges.

Try this:

edgelist =[(0, 1), (0, 2), (1, 2), (0, 3), (2, 3), (2, 4), (3, 4)]

v_list=[]
for edge in edgelist:
    for v in edge:  
        if v not in v_list:
            v_list.append(v)

g.add_vertices(len(v_list))

And then:

G.add_edges(edgelist)

Upvotes: 1

Related Questions