我有一些关系数据想要加载到 NetworkX 中,并最终将其转换为加权图。
本质上,关系边是有向和加权的,我想在转换图形时保留权重属性。使用以下代码,我已经能够将关系边从字典加载到MultiDiGraph():
MG = nx.MultiDiGraph([(i['source'],i['target']) for i in edges ])
Run Code Online (Sandbox Code Playgroud)
然后,我将 转换MultiDiGraph()为 a DiGraph(),并将重复的边压缩为一条,并更新每条边的边权重:
G = nx.DiGraph()
for (u,v) in MG.edges():
G.add_edge(u, v, weight=len(MG[u][v]))
Run Code Online (Sandbox Code Playgroud)
从这里,我想将 转换DiGraph()为 a Graph(),并再次保留并压缩边权重:
g = G.to_undirected()
Run Code Online (Sandbox Code Playgroud)
但我遇到的问题是,它似乎保留了为'a' -> 'b'or找到的第一个边权重'b' -> 'a'。
我想要的是在到达无向边缘时将这些边缘的总和保持为权重。
下面是一个示例,展示了我正在使用的内容:
# relational directed edge data containing duplicate edges
edges = [{'source': 'a', 'target': 'b'},
{'source': 'a', 'target': 'b'},
{'source': 'a', 'target': 'b'},
{'source': 'b', 'target': 'a'},
{'source': 'a', 'target': 'c'},
{'source': 'c', 'target': 'a'},
{'source': 'c', 'target': 'd'},
{'source': 'c', 'target': 'd'},
{'source': 'd', 'target': 'c'}]
# load edges into a MultiDiGraph to maintain direction and duplicate edges
MG = nx.MultiDiGraph([(i['source'],i['target']) for i in edges ])
MG.edges(data=True) = [('a', 'c', {}),
('a', 'b', {}),
('a', 'b', {}),
('a', 'b', {}),
('c', 'a', {}),
('c', 'd', {}),
('c', 'd', {}),
('b', 'a', {}),
('d', 'c', {})]
# convert MultiDiGraph to a DiGraph and update edge weight
G = nx.DiGraph()
for (u,v) in MG.edges():
G.add_edge(u, v, weight=len(MG[u][v]))
G.edges(data=True) = [('a', 'c', {'weight': 1}),
('a', 'b', {'weight': 3}),
('c', 'a', {'weight': 1}),
('c', 'd', {'weight': 2}),
('b', 'a', {'weight': 1}),
('d', 'c', {'weight': 1})]
# convert DiGraph to a Graph, but edge weight not updated as sum, but first value
g = G.to_undirected()
g.edges(data=True) = [('a', 'c', {'weight': 1}),
('a', 'b', {'weight': 1}),
('c', 'd', {'weight': 1})]
Run Code Online (Sandbox Code Playgroud)
最终,我希望无向图中的边权重如下,但我无法弄清楚这是否是 G.to_undirected 的选项或如何执行此操作:
g.edges(data=True) = [('a', 'c', {'weight': 2}),
('a', 'b', {'weight': 4}),
('c', 'd', {'weight': 3})]
Run Code Online (Sandbox Code Playgroud)
小智 5
G.to_undirected() 不能用于控制无向边获取哪些数据,请参阅networkx 文档
您也可以执行以下操作:
import networkx as nx
G = nx.DiGraph()
G.add_edges_from([('a', 'c', {'weight': 1}),
('a', 'b', {'weight': 3}),
('c', 'a', {'weight': 1}),
('c', 'd', {'weight': 2}),
('b', 'a', {'weight': 1}),
('d', 'c', {'weight': 1})])
print G.edges(data=True)
g = nx.Graph()
g.add_edges_from(G.edges_iter(), weight=0)
print g.edges(data=True)
for u, v, d in G.edges_iter(data=True):
g[u][v]['weight'] += d['weight']
print g.edges(data=True)
Run Code Online (Sandbox Code Playgroud)
基本上,您创建一个新的无向图 g 并用有向图 G 中的所有边填充它。此时,您还将边的权重初始化为 0。最后,您只需将权重添加到无向图中的每条边。请注意,在无向图中,边 (u, v) 与 (v, u) 相同。