Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a graph in networkx from a sparse matrix?

I have a fairly large sparse matrix. The sparse matrix have elements in the below format. I want to create a graph network using a networkx library. Now, how should I approach?

Row and column are nodes and they are connected if the value of the matrix element is 1.

In [44]: print(a)

(0, 0)    1
(1, 2)    1
(1, 3)    1
(2, 3)    1
like image 292
vegabond Avatar asked Oct 20 '25 09:10

vegabond


1 Answers

Take a look at

from_scipy_sparse_matrix

The call looks like G=nx.from_scipy_sparse_matrix(A, parallel_edges=False, create_using=None, edge_attribute='weight')

A is the sparse matrix.

If parallel_edges=False, then the entry is considered an edge weight

create_using says what kind of graph it is. It defaults to nx.Graph.

If create_using is MultiGraph of MultiDiGraph, and parallel_edges=True, and all edges are entries, then a 2 would mean 2 edges.

Otherwise the entries are treated as edge attributes.

like image 129
Joel Avatar answered Oct 22 '25 00:10

Joel



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!