Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

r - Perform union of graphs based on vertex names Python igraph

This issue has been filed on github something like 6 months ago, but since it has not yet been fixed I'm wondering whether there is a quick fix that I am missing.

I want to merge two graphs based on their names:

g1 = igraph.Graph()
g2 = igraph.Graph()

# add vertices
g1.add_vertices(["A","B"])
g2.add_vertices(["B","C","D"])

for vertex in g1.vs:
    print vertex.index
0
1

for vertex in g2.vs:
    print vertex.index
0
1
2

However when I perform the union, igraph uses the vertex IDs rather than the names, so I end up with three vertices instead of four (if it was based on names). I guess that because B has index 0 in g2, it is merged with A of g1. And in a similar way, C of g2 is merged with B of g1.

g_union = igraph.Graph.union(g1,g2)

g_union.vs['name'] # of course
KeyError: 'Attribute does not exist'

for vertex in g_union.vs:
    print vertex.index
0
1
2

Any idea on how to bypass this issue? This is possible, since it was done in the R implementation of igraph.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Simply make a new graph, and add vertices by name. Of course, this would eliminate other node properties, which you would also have to add manually.

g1 = igraph.Graph()
g2 = igraph.Graph()

# add vertices
g1.add_vertices(["A","B"])
g2.add_vertices(["B","C","D"])

g3 = igraph.Graph()
verts_to_add = []
for v in g1.vs:
    if v['name'] not in verts_to_add:
        verts_to_add.append(v['name'])
for v in g2.vs:
    if v['name'] not in verts_to_add:
        verts_to_add.append(v['name'])

g3.add_vertices(verts_to_add)

for v in g3.vs:
    print(v['name'])

#A
#B
#C
#D

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...