如何在Networkx中合并MultiDiGraph平行边并设置权重
问题:NetworkX中如何将MultiDiGraph的平行边合并为带权重的DiGraph?
我正在用Python的NetworkX库构建图结构,从包含source和target字段的CSV文件提取边后,得到的边列表如下:
edges = [(a,b), (a,c), (b,c), (a,b), (a,b), (a,c)]
我先基于这些边创建了MultiDiGraph,现在希望将其转换为DiGraph,把相同平行边的出现次数作为权重,目标结果如下:
edges = [(a, b, weight=3), (b, c, weight=1), (a, c, weight=2)]
我已经通过将CSV转为列表再用Counter统计的方式实现了类似功能,代码如下:
reader = csv.reader(open('edges_list.csv', 'r')) next(reader, None) list_edges = list(reader) count = Counter(map(tuple, list_edges)) list = [list(i) for i in count.items()] list = [[k,v,w] for (k,v),w in list]
但我想了解NetworkX是否提供直接的函数,可将MultiDiGraph中的平行边合并为带权重的DiGraph。
解决方案
NetworkX没有专门的一键函数直接完成这个转换,但可以基于已有的MultiDiGraph,通过简洁的代码实现平行边合并,无需回到CSV层面处理:
方法一:遍历边并累加权重
import networkx as nx # 假设已创建好MultiDiGraph multi_digraph = nx.MultiDiGraph([('a','b'), ('a','c'), ('b','c'), ('a','b'), ('a','b'), ('a','c')]) digraph = nx.DiGraph() for u, v, _ in multi_digraph.edges(): if digraph.has_edge(u, v): digraph[u][v]['weight'] += 1 else: digraph.add_edge(u, v, weight=1) # 查看结果边 print(list(digraph.edges(data=True))) # 输出: [('a', 'b', {'weight': 3}), ('a', 'c', {'weight': 2}), ('b', 'c', {'weight': 1})]
方法二:用Counter统计边对后构建DiGraph
import networkx as nx from collections import Counter multi_digraph = nx.MultiDiGraph([('a','b'), ('a','c'), ('b','c'), ('a','b'), ('a','b'), ('a','c')]) # 统计每个(u, v)边对的出现次数 edge_counts = Counter((u, v) for u, v, _ in multi_digraph.edges()) # 构建带权重的DiGraph digraph = nx.DiGraph() for (u, v), count in edge_counts.items(): digraph.add_edge(u, v, weight=count)
这两种方法都直接基于已有的MultiDiGraph操作,比从CSV重新处理更高效,也更贴合NetworkX的图结构使用逻辑。
内容的提问来源于stack exchange,提问作者Moses Casposes
相关产品推荐
相关产品推荐

