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

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

问题描述

我有一个多图对象,并希望将其转换为具有加权边的简单图对象。我查看了networkx文档,似乎无法找到实现此功能的内置函数。我只是想知道是否有人知道networkx中的内置函数可以实现这个目标。我查看了to_directed(),to_undirected()函数,但它们不符合我的目标。 解决方案

通过加权来创建加权多图的加权图:

  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)

#从M $ b $创建加权图G = nx.Graph()
用于u,v,数据在M.edges(data = True):
w = data ['weight']如果数据中的'weight'其他1.0
如果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})]


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天全站免登陆