使用Networkx导出多重有向图

时间:2018-12-09 16:53:22

标签: networkx

我正在尝试从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 个答案:

答案 0 :(得分:1)

以下应该工作-我添加了MultiDiGraph情况所需的缺少索引;根据需要用所需数据替换它。请注意,在2.x版本中,edge属性已替换为adj

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.adj[f[3]][f[2]]['weight'] += 1.0
        else:
            G.add_edge(f[3], f[2])
            G.adj[f[3]][f[2]][0]['timestamp'] = str(f[1])  
            G.adj[f[3]][f[2]][0]['weight'] = 1.0
    nx.write_gexf(G, "graph.gexf")