将边列表加载到图形工具中

Load an edge-list into graph-tool

我想将边列表加载到图形工具中。我列表中的顶点索引不是连续的,所以我希望它们自动添加为 vertex_properties。据我所知,这应该用 add_edge_list 完成,但我发现 vertex_property "name" 没有创建。另一方面,load_graph_from_csv 确实有效:

from graph_tool.all import *
import numpy as np
import pandas as pd
edge_list = [[1,7,1],[7,4,5],[1,4,3]]
G = Graph(directed=False)
G.ep["length"] = G.new_edge_property("int")
eprops = [G.ep["length"]]
G.add_edge_list(edge_list, hashed=True, eprops=eprops)
print(G.vp.keys())
print(G.ep.keys())
Out: 
[]
['length']

所以你看到 G 中没有 vertex_properties。来自 add_edge_list 的图形工具文档:

Optionally, if hashed == True, the vertex values in the edge list are not assumed to correspond to vertex indices directly. In this case they will be mapped to vertex indices according to the order in which they are encountered, and a vertex property map with the vertex values is returned.

现在我发现 load_graph_from_csv 正在按预期工作:

df = pd.DataFrame.from_records(edge_list, columns=['node_1', 'node_2', 'length'])
df.to_csv('edge_list.csv', sep=',', index=False)
G2 = load_graph_from_csv('edge_list.csv', skip_first=True, directed=False, hashed=True, eprop_names=['length'])
print(G2.vp.keys())
print(G2.ep.keys())
print([G2.vp['name'][v] for v in G2.get_vertices()])
Out: 
['name']
['length']
['1', '7', '4']

有人能给我指出正确的方向吗?

答案就在文档中:

"...a vertex property map with the vertex values is returned."

请注意它说的是 "returned",而不是 "added to the internal property map list"。

就这样:

name = G.add_edge_list(edge_list, hashed=True, eprops=eprops)

name是您想要的属性地图。