【问题标题】:How to create a graph in Python using a CSV File data by graph-tool?如何通过图形工具使用 CSV 文件数据在 Python 中创建图形?
【发布时间】:2016-11-27 02:36:25
【问题描述】:

我正在尝试使用 csv 文件中的图形工具 (https://graph-tool.skewed.de) 创建一个图形,其内容如下:

A,B,50
A,C,34
C,D,55
D,D,80
A,D,90
B,D,78

现在我想创建一个图,其中 A、B、C、D 作为节点,第三列编号作为边。我正在使用图形工具库。第三列数字显示了A、B和A、C等共有的项目。

我可以通过“networkx”(read_edgelist 等)来实现,但我想用图形工具来实现。

【问题讨论】:

  • 你希望你的程序有多通用? (即你想绘制你传递的任何 CSV 文件,还是只需要这个?)你能发布你的代码吗?
  • 实际上,我用networkx做了一些代码,但是我没有任何用graph-tool的代码(我不知道如何开始用graph-tool读取边缘)
  • 具体来说,您已经让 CSV 解析器工作了吗?即你的内存中是否已经有类似[[A , B, 50], [A, C, 50]] 的东西?
  • 是的,我能做到!

标签: python csv graph-tool


【解决方案1】:

您可以使用 add_edge_list() 来添加边列表。如果它们存储的名称与自动分配的索引不同,它将返回一个包含列表中名称的字符串列表。

示例:

from graph_tool.all import *
import csv

g=Graph(directed=False)
csv_E = csv.reader(open('*text_input*'))

e_weight=g.new_edge_property('float')
v_names=g.add_edge_list(csv_E,hashed=True,string_vals=True,eprops=[e_weight])  
#this will assign the weight to the propery map *e_weight* and the names to *v_names*

graph_draw(g, vertex_text=v_names)

【讨论】:

    【解决方案2】:

    假设您已经知道如何在 Python 中读取 CSV 文件(例如,使用CSV library),网站上的文档explain how to do this very clearly.

    类似

    import graph_tool
    g = Graph(directed=False)
    
    
    # this is the result of csv.parse(file)
    list_of_edges = [['A', 'B', 50], ['A','C',34], ['C','D',55], ['D','D',80], ['A','D',90], ['B','D',78]]
    
    vertices = {}
    
    for e in list_of_edges:
        if e[0] not in vertices:
            vertices[e[0]] = True
        if e[1] not in vertices:
            vertices[e[1]] = True
    
    
    for d in vertices:
        vertices[d] = g.add_vertex()
    
    for edge in list_of_edges:
        g.add_edge(vertices[edge[0]], vertices[edge[1]])
    

    【讨论】:

    • 谢谢,我已经测试过了,但是如果我想在节点中显示标签而不是索引号呢?我正在使用此代码绘制图形:graph_draw(g, vertex_text=g.vertex_index, vertex_font_size=18, output_size=(800, 800), output="two-nodes.png")
    猜你喜欢
    • 2016-07-06
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    • 2015-11-30
    • 2014-04-29
    相关资源
    最近更新 更多