NetworkX通过平均并行长度将MultiGraph转换为简单的Graph

时间:2017-08-13 23:38:54

标签: python graph average networkx

有一种解决方案是使用Maehler的代码将MultiGraph转换为Simple Graph

import networkx as nx

G = nx.MultiGraph()
G.add_nodes_from([1,2,3])
G.add_edges_from([(1, 2), (1, 2), (1, 3), (2, 3), (2, 3)])

G2 = nx.Graph(G)

和另一个使用Aslak和Aric的代码来计算权重

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_iter(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})]

想知道如何平均平行边缘的重量?

1 个答案:

答案 0 :(得分:0)

这是一种类似于使用统计包来计算边权重均值的方法。

import networkx as nx
from statistics import mean
# weighted MultiGraph
M = nx.MultiGraph()
M.add_edge(1,2,weight=7)
M.add_edge(1,2,weight=20)
M.add_edge(2,3,weight=42)
M.add_edge(2,3)
# create weighted graph G from M
G = nx.Graph()
for u,v,data in M.edges(data=True):
    if not G.has_edge(u,v):
        # set weight to 1 if no weight is given for edge in M
        weight = mean(d.get('weight',1) for d in M.get_edge_data(u,v).values())
        G.add_edge(u, v, weight=weight)
print(G.edges(data=True))

OUTPUT(networkx-2.0-dev)

EdgeView([(1,2,{'weight':13.5}),(2,3,{'weight':21.5})])