我正在尝试从csv文件构建一个多路复用的有向图,其中每个边都有一个时间戳 . 我想将它导出到Gephi,以便作为动态图进行分析 .
csv文件如下所示:
cdv = [['id','timestamp', 'node 1', 'node 2', 'description']
['1','10', '1', '2', 'description']
['2','20', '1', '3', 'description']
['3,'30', '2', '3', 'description']]
etc.
构建图的代码是:
def csv2gexf(csvf):
G = nx.MultiDiGraph() # works with G = nx.DiGraph()
for f in csv:
if f[3] not in G:
G.add_node(f[3])
if f[2] not in G:
G.add_node(f[2])
G.node[f[2]]['description'] = f[4]
if G.has_edge(f[3], f[2]):
G.edge[f[3]][f[2]]['weight'] += 1.0
else:
G.add_edge(f[3], f[2])
G.edge[f[3]][f[2]]['timestamp'] = str(f[1])
G.edge[f[3]][f[2]]['weight'] = 1.0
nx.write_gexf(G, "graph.gexf")
虽然这段代码在使用DiGraph而不是MultiDiGraph时起作用,但后者给了我这个:
nx.write_gexf(G, "graph.gexf")
File "<decorator-gen-206>", line 2, in write_gexf
File "/usr/local/lib/python3.6/site-packages/networkx/utils/decorators.py", line 220, in _open_file
result = func(*new_args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/networkx/readwrite/gexf.py", line 77, in write_gexf
writer.add_graph(G)
File "/usr/local/lib/python3.6/site-packages/networkx/readwrite/gexf.py", line 300, in add_graph
self.add_edges(G,graph_element)
File "/usr/local/lib/python3.6/site-packages/networkx/readwrite/gexf.py", line 355, in add_edges
for u,v,key,edge_data in edge_key_data(G):
File "/usr/local/lib/python3.6/site-packages/networkx/readwrite/gexf.py", line 340, in edge_key_data
edge_data=data.copy()
AttributeError: 'str' object has no attribute 'copy'
我认为gexf文件格式应该处理多重有向图,我在这里做错了什么?
1 回答
以下应该可行 - 我添加了MultiDiGraph案例所需的缺失索引;根据需要将其替换为所需数据 . 请注意2.x中
edge
属性替换为adj
: