这个问题已经在github年提交,就像6个月前一样,但由于它尚未修复,我想知道是否有一个我错过的快速修复.
我想根据他们的名字合并两个图表:
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
然而,当我执行联合时,igraph使用顶点ID而不是名称,所以我最终得到三个顶点而不是四个(如果它基于名称).我想因为B在g2中有索引0,所以它与g1的A合并.并且以类似的方式,g2的C与g1的B合并.
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
有关如何绕过这个问题的任何想法?这是可能的,因为它是在igraph的R实现中完成的.
解决方法:
只需创建一个新图形,然后按名称添加顶点.当然,这将消除其他节点属性,您还必须手动添加这些属性.
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