根据顶点名称 Python igraph 执行图的并集 [英] Perform union of graphs based on vertex names Python igraph
问题描述
这个问题已经在 github 上提交了,大约 6 个月前,但自从它尚未修复,我想知道是否有我遗漏的快速修复.
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
在g2
中有索引0
,所以它与g1<的
A
合并/代码>.以类似的方式,g2
的C
与g1
的B
合并.
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屋!