networkx.convert_matrix.from_scipy_sparse_matrix¶
- from_scipy_sparse_matrix(A, parallel_edges=False, create_using=None, edge_attribute='weight')[source]¶
Creates a new graph from an adjacency matrix given as a SciPy sparse matrix.
- Parameters
- A: scipy sparse matrix
An adjacency matrix representation of a graph
- parallel_edgesBoolean
If this is True,
create_usingis a multigraph, andAis an integer matrix, then entry (i, j) in the matrix is interpreted as the number of parallel edges joining vertices i and j in the graph. If it is False, then the entries in the matrix are interpreted as the weight of a single edge joining the vertices.- create_usingNetworkX graph constructor, optional (default=nx.Graph)
Graph type to create. If graph instance, then cleared before populated.
- edge_attribute: string
Name of edge attribute to store matrix numeric value. The data will have the same type as the matrix entry (int, float, (real,imag)).
Notes
For directed graphs, explicitly mention create_using=nx.DiGraph, and entry i,j of A corresponds to an edge from i to j.
If
create_usingisnetworkx.MultiGraphornetworkx.MultiDiGraph,parallel_edgesis True, and the entries ofAare of typeint, then this function returns a multigraph (constructed fromcreate_using) with parallel edges. In this case,edge_attributewill be ignored.If
create_usingindicates an undirected multigraph, then only the edges indicated by the upper triangle of the matrixAwill be added to the graph.Examples
>>> import scipy as sp >>> import scipy.sparse # call as sp.sparse >>> A = sp.sparse.eye(2, 2, 1) >>> G = nx.from_scipy_sparse_matrix(A)
If
create_usingindicates a multigraph and the matrix has only integer entries andparallel_edgesis False, then the entries will be treated as weights for edges joining the nodes (without creating parallel edges):>>> A = sp.sparse.csr_matrix([[1, 1], [1, 2]]) >>> G = nx.from_scipy_sparse_matrix(A, create_using=nx.MultiGraph) >>> G[1][1] AtlasView({0: {'weight': 2}})
If
create_usingindicates a multigraph and the matrix has only integer entries andparallel_edgesis True, then the entries will be treated as the number of parallel edges joining those two vertices:>>> A = sp.sparse.csr_matrix([[1, 1], [1, 2]]) >>> G = nx.from_scipy_sparse_matrix( ... A, parallel_edges=True, create_using=nx.MultiGraph ... ) >>> G[1][1] AtlasView({0: {'weight': 1}, 1: {'weight': 1}})