我使用networkx中的 MultiDiGraph 函数创建了一个图形,并添加了按边缘出现频率对边缘的权重。现在,我正在考虑创建一个 DiGraph 图,并删除所有多个边缘和自循环,同时仍保留多个边缘和自循环的权重。例如,如果边缘之一在MultiDiGraph中出现5次并且相应的权重为5,则在创建DiGraph并删除所有多个边缘和自环时,该边缘的权重仍应为5。如何做到这一点?非常感谢!
分别创建两个图形
G1 = nx.MultiDiGraph()
G1.add_edges_from(
[(3,4),(3,5),(3,7),(4,7),(6,7),(4,5),(5,6),(3,6),(4,5),(4,5),(6,3),(3,3)],
color='red'
)
G2 = nx.MultiDiGraph()
G2.add_edges_from(
[(2,5),(2,8),(4,8),(6,8),(4,5),(4,5),(5,6),(2,6),(6,2)],
color='red'
)
提取这两个图的节点和边的并集
union_nodes=list(set(list(G1.nodes)+list(G2.nodes)))
union_edges=list(list(G1.edges())+list(G2.edges()))
创建结合这两个图的新图
G=nx.MultiDiGraph()
G.add_nodes_from(union_nodes)
G.add_edges_from(union_edges)
通过边缘出现的频率为边缘添加权重
from collections import Counter
c = Counter(G.edges())
for u, v, d in G.edges(data=True):
d['weight'] = c[u, v]
print(list(G.edges(data=True)))
nx.draw_networkx(G, width=[d['weight'] for _, _, d in G.edges(data=True)])
答案 0 :(得分:1)
您可以创建DiGraph
的边缘,直接为其分配相应的权重:
c = Counter(G.edges())
simple_digraph = nx.DiGraph()
for u, v, d in G.edges(data=True):
# avoid repeating edges and self-loops
if not simple_digraph.has_edge(u, v) and u != v:
simple_digraph.add_edge(u, v, weight=c[u, v])
print(list(simple_digraph.edges(data=True)))
输出:
[
(2, 5, {'weight': 1}), (2, 8, {'weight': 1}), (2, 6, {'weight': 1}),
(5, 6, {'weight': 2}), (6, 7, {'weight': 1}), (6, 3, {'weight': 1}),
(6, 8, {'weight': 1}), (6, 2, {'weight': 1}), (3, 4, {'weight': 1}),
(3, 5, {'weight': 1}), (3, 7, {'weight': 1}), (3, 6, {'weight': 1}),
(4, 7, {'weight': 1}), (4, 5, {'weight': 5}), (4, 8, {'weight': 1})
]