根据顶点名称Python igraph执行图的联合 [英] Perform union of graphs based on vertex names Python igraph

查看:368
本文介绍了根据顶点名称Python igraph执行图的联合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题已在6个月前的 github 上提交,但自它还没有被修复我想知道是否有一个快速修复,我失踪。

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

然而,当我执行联合时,igraph使用顶点ID而不是名称,所以我最终得到三个顶点而不是四个顶点(如果它是基于名称的话)。我猜这是因为 B 的索引 0 g2 中,它与 g1 合并。以类似的方式, g2 C B of g1

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

有关如何绕过此问题的任何想法?这是可能的,因为它是在igraph的R实现中完成的。

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

推荐答案

只需创建一个新图并通过添加顶点名称。

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

这篇关于根据顶点名称Python igraph执行图的联合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆