Memory-efficient numeric arrays
Large matrices with relatively few nonzero entries
SciPy · Module
scipy.sparse provides sparse-array formats that store data efficiently when most positions are empty. Its formats support different construction, arithmetic, slicing, linear-algebra, and graph-computation workloads.
The module represents mostly empty numeric arrays by storing only nonzero entries in a selected sparse format. Choose a format according to the access or computation pattern, and convert between formats when another operation is better served by a different representation.
import scipy.sparsefrom scipy.sparse import csr_array
A = csr_array(([1, 2, 3], ([0, 1, 2], [0, 2, 1])), shape=(3, 3))
print(A @ A)
Builds a CSR sparse array from nonzero values and coordinates, then performs sparse matrix multiplication.
Large matrices with relatively few nonzero entries
Matrix-vector products and row-oriented slicing
Graphs represented by sparse adjacency structures
Incrementally assembling sparse data
scipy.sparse provides tools for arrays in which only a small number of locations contain data. Avoiding storage for the many empty locations can reduce memory use and enable faster linear-algebra or graph computations.
Follow-up: Which related SciPy areas use sparse arrays? scipy.sparse.linalg supports linear algebra, while scipy.sparse.csgraph supports graph-based computations.
CSR is suited to fast arithmetic, vector products, and row slicing. CSC has similar strengths for column slicing, so the choice should follow the dominant access pattern.
Follow-up: What format is a reasonable construction starting point? COO is simple to construct and can be converted quickly to CSR, CSC, or BSR.
The module offers several formats with different trade-offs: BSR for contiguous blocks, COO for construction and in-place modification, CSR for row-oriented operations, CSC for column-oriented operations, and DIA when values lie mainly on diagonals.
Follow-up: Why not use one universal format? Sparse operations and storage layouts are optimized for different data patterns and access patterns.
scipy.sparse.bsr_arrayscipy.sparse.coo_arrayscipy.sparse.csr_arrayscipy.sparse.csc_arrayscipy.sparse.dia_arrayscipy.sparse.linalgscipy.sparse.csgraph