Networkx : Convert multigraph into simple graph with weighted edges

前端 未结 3 774
名媛妹妹
名媛妹妹 2020-12-08 08:10

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 fin

3条回答
  •  孤城傲影
    2020-12-08 08:48

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

提交回复
热议问题