Networkx : Convert multigraph into simple graph with weighted edges

Question:

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.

Asked By: anonuser0428

||

Answers:

You can use igraph library. Download python extension module from here:
http://igraph.sourceforge.net/download.html

Answered By: Fractal

One very simple way of doing it is just to pass your multigraph as input to 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)

This will create an undirected graph of your multigraph where multiple edges are merged into single edges. However, if you have different attributes for the edges that get merged, I don’t know if there’s any way of determining which attribute is kept.

Answered By: Maehler

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})]
Answered By: Aric
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.