将数据列表(表示边)加载到python中的igraph图中

我有一些列表格式的关系数据,我想导入到iGraph.Graph()中.列表列表包含重复的边,最终,我想为重复边添加边权重.然而,目前,当我试图将图形边缘添加到减去权重因子时,我无法弄清楚我做错了什么.

我认为问题是我必须首先将所有顶点导入到图形中,然后我可以在顶点之间添加边缘,但似乎并非如此.

将这些边加载到图中我做错了什么?

*如何修改边缘加载过程以首先查找图形中的边缘,如果未找到,则添加边缘,如果找到,则将该边缘的权重增加1,*

数据

In [60]:    edges

Out[60]:    [['a', 'b'],
             ['a', 'b'],
             ['a', 'b'],
             ['b', 'a'],
             ['a', 'c'],
             ['c', 'a'],
             ['c', 'd'],
             ['c', 'd'],
             ['d', 'c'],
             ['d', 'c']]

IGRAPH代码将图形加载到图形和错误中

In [61]:    # extract vertices for edges list
            vertices = []
            for line in edges:
                nodes.append(line[0])
                nodes.append(line[1])

            # find unique vertices
            uniq_vertices = set(sorted(nodes))

In [62]:    # create an empty graph
            g = igraph.Graph()

In [63]:    # add vertices to the graph
            g.add_vertices(uniq_vertices)

In [64]:    # for each line in the edges list, check to see if it's already in the graph, and if not, add it to the graph.
           for line in edges:
                 if not line in g.get_edgelist():
                     g.add_edges(edges)     

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-64-04a376c78860> in <module>()
      2 for line in edges:
      3     if not line in g.get_edgelist():
----> 4         g.add_edges(edges)

C:\Users\Curtis\Anaconda\lib\site-packages\igraph\__init__.pyc in add_edges(self, es)
    228           endpoints. Vertices are enumerated from zero.
    229         """
--> 230         return GraphBase.add_edges(self, es)
    231 
    232     def add_vertex(self, name=None, **kwds):

ValueError: no such vertex: 'a'

解决方法:

问题可能就在这里(至少这部分代码对我来说没有意义):

for line in edges:
    if not line in g.get_edgelist():
        g.add_edges(edges)

在这里检查行是否在g.get_edgelist()中,并确保它不会是因为你的边列表包含列表,而g.get_edgelist()则返回元组.然后添加所有边,而不仅仅是已检查的边.

我附加了代码的替代版本,似乎可以帮我完成工作.请注意,在创建图形时我没有消除多个边缘 – 我添加它们然后只需要求igraph将它们折叠成一个并将它们的权重相加:

import igraph

edges = [['a', 'b'],
         ['a', 'b'],
         ['a', 'b'],
         ['b', 'a'],
         ['a', 'c'],
         ['c', 'a'],
         ['c', 'd'],
         ['c', 'd'],
         ['d', 'c'],
         ['d', 'c']]

# collect the set of vertex names and then sort them into a list
vertices = set()
for line in edges:
    vertices.update(line)
vertices = sorted(vertices)

# create an empty graph
g = igraph.Graph()

# add vertices to the graph
g.add_vertices(vertices)

# add edges to the graph
g.add_edges(edges)

# set the weight of every edge to 1
g.es["weight"] = 1

# collapse multiple edges and sum their weights
g.simplify(combine_edges={"weight": "sum"})
上一篇:从python-igraph获取顶点列表


下一篇:全局规划——从零开始到A*(深蓝笔记)