具有 add_edges_from 的图形工具顶点标签

Graph-tool vertex label with add_edges_from

我尽力在网上寻找解决方案,但似乎找不到适合我的 graph_tool 网络的解决方案。我有一个 pandas 数据框 df,它包含三列:id_sourceid_targetweightid_sourceid_target 包含文本形式的名称。我想将它们用作顶点标签。但是,从 pandas 数据帧添加边时,我必须设置 hashed=True。代码看起来像这样

from graph_tool.all import *

g = Graph()
eweight = g.new_ep('double')
vmap = g.add_edge_list(df.values, eprops=[eweight], hashed=True)

我的objective是画这个带有顶点标签的小网络。当我不知道通过 g.add_edge_list() 函数在图中引入每个新节点的顺序时,我被卡住了,无法找出如何添加该顶点 属性 的解决方案。

我应该先添加顶点吗?然后在图上执行 add_edge_list 函数。第二步会识别顶点名称(或标签)吗?

来自 Graph.add_edge_list 的文档:

Add a list of edges to the graph, given by edge_list, which can be an iterator of (source, target) pairs where both source and target are vertex indexes, or a numpy.ndarray of shape (E,2), where E is the number of edges, and each line specifies a (source, target) pair. If the list references vertices which do not exist in the graph, they will be created.

您已通过 df.valuesedge_list,它有三列(即 (E, 3) 的形状),但预计有两列((E, 2) 的形状).

试试这个:

g.add_edge_list(df[['id_source', 'id_target']].to_numpy(), eprops=[eweight], hashed=True)

我怀疑eprops应该是df['weight'],但我不确定。

答案就在vmap中。它一直在那里。当您索引 vmap 时,它将获取标签名称。

  • vmap[0] 将是记录的第一个顶点的标签。
  • vmap[1]第二个,以此类推