Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Networkx: convert a MultiDiGraph to DiGraph

Is there a quick method to convert a networkx MultiDiGraph object to DiGraph? I am creating a scale_free_graph using this code:

import networkx as nx
G = nx.scale_free_graph(100)

But I would like to remove all self loops and parallel edges from my graph.

like image 419
Ohm Avatar asked Jun 24 '26 01:06

Ohm


1 Answers

You can create the new nx.DiGraph using the nx.MultiDiGraph as input graph:

incoming_graph_data (input graph (optional, default: None)) – Data to initialize graph. If None (default) an empty graph is created. The data can be an edge list, or any NetworkX graph object. If the corresponding optional Python packages are installed the data can also be a NumPy matrix or 2d ndarray, a SciPy sparse matrix, or a PyGraphviz graph.

import networkx as nx

G = nx.MultiDiGraph()
G.add_edges_from([
    (1, 2),
    (1, 2),
    (1, 2)
])
print('G edges:', G.edges)
H = nx.DiGraph(G)
print('H edges:', H.edges)

Will print:

G edges: [(1, 2, 0), (1, 2, 1), (1, 2, 2)]
H edges: [(1, 2)]
like image 109
vurmux Avatar answered Jun 25 '26 13:06

vurmux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!