SciPy Sparse Data
A sparse matrix is one where most entries are zero. They show up constantly: a social network where each person knows a handful of the billions of users, a document–word table where each document uses a tiny fraction of the vocabulary, the stiffness matrix of a finite-element model. Storing all those zeros wastes memory and time, so scipy.sparse stores only the non-zero values and their positions.
import numpy as np
from scipy import sparse
dense = np.array([
[0.0, 0.0, 3.0, 0.0],
[4, 0, 0, 0],
[0, 0, 0, 5],
])
m = sparse.csr_array(dense)
print(m)
print("shape:", m.shape, " stored values:", m.nnz)<Compressed Sparse Row sparse array of dtype 'float64'
with 3 stored elements and shape (3, 4)>
Coords Values
(0, 2) 3.0
(1, 0) 4.0
(2, 3) 5.0
shape: (3, 4) stored values: 3
Printing a sparse array lists each stored entry as (row, column) value. Only three numbers are kept instead of twelve.
Dense versus sparse memory
The savings grow quickly with size. A 2000 × 2000 matrix with 1% non-zero values:
import numpy as np
from scipy import sparse
rng = np.random.default_rng(1)
m = sparse.random_array((2000, 2000), density=0.01, format="csr", random_state=rng)
dense_bytes = m.toarray().nbytes
sparse_bytes = m.data.nbytes + m.indices.nbytes + m.indptr.nbytes
print("non-zeros :", m.nnz)
print("dense (MB) :", round(dense_bytes / 1e6, 2))
print("sparse (MB) :", round(sparse_bytes / 1e6, 2))non-zeros : 40000
dense (MB) : 32.0
sparse (MB) : 0.49
Sparse formats
There is no single best way to store a sparse matrix, so SciPy offers several formats. You usually build a matrix in one format and compute with another:
| Format | Class | Strength |
|---|---|---|
| COO (coordinate) | coo_array |
Easy construction from (row, col, value) triples |
| CSR (compressed sparse row) | csr_array |
Fast row slicing, matrix–vector products, arithmetic |
| CSC (compressed sparse column) | csc_array |
Fast column slicing, used by many solvers |
| LIL (list of lists) | lil_array |
Changing the sparsity pattern element by element |
| DOK (dictionary of keys) | dok_array |
Random element access and updates |
| DIA (diagonal) | dia_array |
Banded matrices |
Note: SciPy has both
*_arrayclasses (new, behave like NumPy arrays) and older*_matrixclasses (behave like the deprecatednp.matrix). Prefer the_arrayversions in new code: with them*is element-wise and@is matrix multiplication, just as with NumPy.
Building from coordinates
Often your data arrives as a list of "who–what–how much" records. COO format takes them directly, then you convert to CSR for computing. Duplicate coordinates are summed during conversion, which is handy for counting:
import numpy as np
from scipy import sparse
# purchases: (customer, product, quantity)
rows = np.array([0, 0, 1, 2, 2, 0])
cols = np.array([1, 3, 0, 3, 2, 1])
qty = np.array([2, 1, 5, 1, 4, 3])
purchases = sparse.coo_array((qty, (rows, cols)), shape=(3, 4)).tocsr()
print(purchases.toarray())
print("customer 0 total items:", purchases[[0], :].sum())[[0 5 0 1]
[5 0 0 0]
[0 0 4 1]]
customer 0 total items: 6
Inside CSR
A CSR array keeps three NumPy arrays:
data— the non-zero values, row by rowindices— the column of each valueindptr— where each row starts indata(rowiisdata[indptr[i]:indptr[i+1]])
import numpy as np
from scipy import sparse
m = sparse.csr_array(np.array([
[1, 0, 2],
[0, 0, 0],
[3, 4, 0],
]))
print("data :", m.data)
print("indices:", m.indices)
print("indptr :", m.indptr)
print("row 2 values:", m.data[m.indptr[2]:m.indptr[3]])data : [1 2 3 4]
indices: [0 2 0 1]
indptr : [0 2 2 4]
row 2 values: [3 4]
Row 1 is empty, which is why indptr repeats the value 2.
Working with sparse arrays
Sparse arrays support the operations you'd expect, and stay sparse whenever the result is sparse:
import numpy as np
from scipy import sparse
a = sparse.csr_array(np.array([[1, 0, 0], [0, 2, 0], [0, 0, 3]]))
v = np.array([10, 20, 30])
print("a @ v :", a @ v)
print("a * 2 nnz :", (a * 2).nnz)
print("row sums :", a.sum(axis=1))
print("transpose is", type(a.T).__name__)
a_lil = a.tolil()
a_lil[0, 2] = 7 # LIL is cheap to modify
print(a_lil.tocsr().toarray())
a.eliminate_zeros() # drop any explicitly stored zeros
print("identity nnz:", sparse.eye_array(1000).nnz)a @ v : [10 40 90]
a * 2 nnz : 3
row sums : [1 2 3]
transpose is csc_array
[[1 0 7]
[0 2 0]
[0 0 3]]
identity nnz: 1000
Tip: Avoid calling
.toarray()on a huge sparse matrix — it allocates every zero. Use it only for small examples or after slicing out a small piece.
Test yourself
What does a sparse matrix store?
- Every element, compressed with zip
- Only the non-zero values and their positions
- Only the zeros
- The matrix rounded to integers
Which format is best for fast row slicing and matrix–vector products?
- COO
- LIL
- CSR
- DOK
When converting COO to CSR, what happens to duplicate (row, col) entries?
- The last one wins
- They raise an error
- They are summed
- They are dropped