如何使用Python Networkx存储边的信息?



我使用NetworkX将字典转换成图形。除了一条边的源和目的信息,字典还包含了这条边的元数据,比如这条边的名称和与这条边相关的概率值。这个图也包含平行边。这是字典的前两个键的前两个键值对。你可以注意到在节点25255942和72359602之间有两条平行的边,它们的名称和概率不同。

{25255942: {52691892: [('Internet of Things (IOT) Device Management',
0.4444444444444444)],
72359602: [('Internet of Things (IOT) Device Management', 1.0),
('Questions', 0.07692307692307693)]},
185589766: {183701781: [('"Cloud Computing" How to use it for your business',
0.4),
('Learn How to Be a Success in Network Marketing', 0.16666666666666666)],
183702935: [('"Cloud Computing" How to use it for your business', 0.4),
('Learn How to Be a Success in Network Marketing', 0.16666666666666666)],
110069642: [('Learn How to Be a Success in Network Marketing',
0.3333333333333333),
('How to make money in network marketing', 1.0)]}}

如果我简单地把这个字典转换成一个图,并通过这个命令g.edges()打印边,它看起来像下面,我的意思是,丢失了元数据和关于平行边的信息。

[(25255942, 52691892), (25255942, 72359602), .....]

是否有一种方法可以使用NetworkX创建图形而不丢失任何信息?

您可以使用add_edges_from一次添加多个边。对于平行边,请参考具有自环和平行边的多向图。

import networkx as nx
import matplotlib.pyplot as plt   
from pprint import pprint
G = nx.MultiDiGraph()
# For each edge, we should assign source, destination, and attributes.
first_edge = (
25255942, 
52691892, 
{'name': 'Internet of Things (IOT) Device Management', 'probability': 0.4444444444444444},
)
second_edge = (
25255942, 
72359602, 
{'name': 'Internet of Things (IOT) Device Management', 'probability': 1.0},
)
third_edge = (
25255942, 
72359602, 
{'name': 'Questions', 'probability': 0.07692307692307693},
)
edges = [first_edge, second_edge, third_edge]
G.add_edges_from(edges)
pprint(list(G.edges(data=True)))

pprint(list(G.edges(data=True)))的输出将为:

[(25255942,
52691892,
{'name': 'Internet of Things (IOT) Device Management',
'probability': 0.4444444444444444}),
(25255942,
72359602,
{'name': 'Internet of Things (IOT) Device Management', 'probability': 1.0}),
(25255942,
72359602,
{'name': 'Questions', 'probability': 0.07692307692307693})]

你可以为每条边添加一个字典,并以这种方式访问它:

G.edges[25255942, 52691892]['name']

文档中有一个很好的例子:

>>> G = nx.path_graph(3)  # or MultiGraph, etc
G.add_edge(2, 3, weight=5)
[e for e in G.edges]
[(0, 1), (1, 2), (2, 3)]
G.edges.data()  # default data is {} (empty dict)
EdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})])
G.edges.data("weight", default=1)
EdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)])
G.edges([0, 3])  # only edges from these nodes
EdgeDataView([(0, 1), (3, 2)])
G.edges(0)  # only edges from node 0
EdgeDataView([(0, 1)])

最新更新