将字典元组转换为networkx.Graph

时间:2018-08-02 11:06:45

标签: python graph networkx

我有一个无向图:G,它具有节点,边和权重。我是通过DataFrame使用它创建的:

G = nx.Graph()
for key,value in df_couple.iterrows():   
    from_point = str(value[0])
    to_point = str(value[1])
    edgeweight = float(value[2])
    G.add_weighted_edges_from([(from_point, to_point, edgeweight)])

然后,我计算所有节点之间的最短距离,使用:

dis = nx.all_pairs_dijkstra_path_length(G, cutoff=None, weight='weight')

我检查dis的类型是'generator',所以我使用:

In [23]:item = next(dis)

In [24]:item

Out[24]: 
('13537625459___1020004',
 {'13537625459___1020004': 0,
  '20-72-0D-39-01-6E___1020002': 0.40973195335611445,
  '20-72-0D-39-01-89___1020002': 0.24834431946516566,
  '20-72-0D-39-01-8A___1020002': 0.40973195335611445,
  '20-72-0D-39-01-8B___1020002': 0.40973195335611445,
  '20-72-0D-39-01-8D___1020002': 0.24026806227171532,
  '20-72-0D-39-02-96___1020002': 0.40973195335611445,
  '20-72-0D-39-02-A3___1020002': 0.40973195335611445,
  '20-72-0D-39-02-D4___1020002': 0.3179114489450109,
  '20-72-0D-39-02-DF___1020002': 0.23809674037229048,
  '20-72-0D-39-02-EF___1020002': 0.18307326555472847,
  '20-72-0D-39-02-F8___1020002': 0.23809674037229048})

In [25]:type(item)
Out[25]: tuple

下一步,我需要将项目(或dis)转换为[nx.Graph]格式,所以我使用:

G_dis = nx.Graph(dict([item]))

然后我发现只有节点,边缘是成功的,但重量不是:

    In [28]:G_dis.nodes()
    Out[28]: NodeView(('13537625459___1020004', '20-72-0D-39-02EF___1020002', 
    '20-72-0D-39-02-DF___1020002', '20-72-0D-39-02-F8___1020002',
    '20-72-0D-39-01-8D___1020002', '20-72-0D-39-01-89___1020002', 
    '20-72-0D-39-02-D4___1020002', '20-72-0D-39-01-8A___1020002',
    '20-72-0D-39-01-8B___1020002', '20-72-0D-39-02-96___1020002', 
    '20-72-0D-39-02-A3___1020002', '20-72-0D-39-01-6E___1020002'))

    In [29]:G_dis.edges()
    Out[29]: EdgeView([('13537625459___1020004', '13537625459___1020004'), 
    ('13537625459___1020004', '20-72-0D-39-02-EF___1020002'), 
    ('13537625459___1020004', '20-72-0D-39-02-DF___1020002'), 
    ('13537625459___1020004', '20-72-0D-39-02-F8___1020002'), 
    ('13537625459___1020004', '20-72-0D-39-01-8D___1020002'), 
    ('13537625459___1020004', '20-72-0D-39-01-89___1020002'), 
    ('13537625459___1020004', '20-72-0D-39-02-D4___1020002'), 
    ('13537625459___1020004', '20-72-0D-39-01-8A___1020002'), 
    ('13537625459___1020004', '20-72-0D-39-01-8B___1020002'), 
    ('13537625459___1020004', '20-72-0D-39-02-96___1020002'), 
    ('13537625459___1020004', '20-72-0D-39-02-A3___1020002'), 
    ('13537625459___1020004', '20-72-0D-39-01-6E___1020002')])


  In[30]:G_dis.get_edge_data('13537625459___1020004','13537625459___1020004')
  Out[30]: {}

为什么权重为{}?,它应为'0.40973195335611445'之类的浮点数,但转换后为空。

我尝试了networkx中的nx.from_dict_of_dicts(d); nx.from_dict_of_lists(d)和其他类似的函数,但是没用。

1 个答案:

答案 0 :(得分:0)

我认为您对G_dis的构造是错误的。像创建G一样尝试使用元组。

这应该有效:

G_dis = nx.Graph()
for p1, d in nx.all_pairs_dijkstra_path_length(G, cutoff=None, weight='weight'):
    for p2, w in d.items():
        G_dis.add_weighted_edges_from([(p1, p2, w)])