我使用networkx中的MultiDiGraph函数创建了一个图表,并添加了按边出现频率对边进行权重。现在我正在考虑创建一个有向图图并删除所有多边和自循环,同时仍然保留多边和自循环的权重。例如,如果某条边在 MultiDiGraph 中出现了 5 次,对应的权重为 5,则在创建有向图并删除所有多条边和自环时,该边的权重仍应为 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)])
最佳答案
您可以直接创建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})
]
关于python - 如何在networkx中进行有向图,在删除所有多条边和自循环时保留多条边和自循环的权重,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52898429/