Networkx:将多图转换为带加权边的简单图 [英] Networkx : Convert multigraph into simple graph with weighted edges

查看:34
本文介绍了Networkx:将多图转换为带加权边的简单图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多图对象,想将其转换为带有加权边的简单图形对象.我已经浏览了 networkx 文档,但似乎找不到内置函数来实现这一点.我只是想知道是否有人知道 networkx 中可以实现此目标的内置函数.我查看了 to_directed() 、 to_undirected() 函数,但它们不符合我的目标.

I have a multigraph object and would like to convert it to a simple graph object with weighted edges. I have looked through the networkx documentation and can't seem to find a built in function to achieve this. I was just wondering if anyone knew of a built-in function in networkx that could achieve this goal. I looked at the to_directed() , to_undirected() functions but they don't serve my goal.

推荐答案

以下是一种通过对权重求和从加权多重图创建加权图的方法:

Here is one way to create a weighted graph from a weighted multigraph by summing the weights:

import networkx as nx
# weighted MultiGraph
M = nx.MultiGraph()
M.add_edge(1,2,weight=7)
M.add_edge(1,2,weight=19)
M.add_edge(2,3,weight=42)

# create weighted graph from M
G = nx.Graph()
for u,v,data in M.edges(data=True):
    w = data['weight'] if 'weight' in data else 1.0
    if G.has_edge(u,v):
        G[u][v]['weight'] += w
    else:
        G.add_edge(u, v, weight=w)

print(G.edges(data=True))
# [(1, 2, {'weight': 26}), (2, 3, {'weight': 42})]

这篇关于Networkx:将多图转换为带加权边的简单图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆