Large numeric arrays often contain far more zeros than useful values. SciPy sparse arrays keep the stored values and their coordinates, which makes them suitable for graph edges, feature matrices, and assembled numerical systems.
The COO format accepts aligned value, row, and column arrays in any order. An explicit shape preserves empty trailing rows or columns, while repeated coordinates can remain separate during assembly.
Converting COO data to CSR sums repeated coordinates and prepares the array for efficient row operations and matrix-vector multiplication. Dense conversion is appropriate only for the small inspection used here because toarray() allocates space for every zero.
import numpy as np from scipy.sparse import coo_array row = np.array([0, 0, 1, 2, 2]) col = np.array([0, 2, 2, 0, 0]) values = np.array([10, 3, 8, 4, 6], dtype=float)
The last two values share coordinate (2, 0), and the fourth column is intentionally empty.
coo = coo_array((values, (row, col)), shape=(3, 4)) print("COO format:", coo.format) print("Shape:", coo.shape) print("Stored coordinate entries:", coo.nnz)
$ python3 sparse_array_create.py COO format: coo Shape: (3, 4) Stored coordinate entries: 5
csr = coo.tocsr() print("CSR format:", csr.format) print("Stored positions after conversion:", csr.nnz) print("Dense check:") print(csr.toarray())
toarray() materializes every zero, so keep large datasets sparse.
weights = np.array([1.0, 2.0, 0.5, 0.0]) product = csr @ weights np.testing.assert_allclose(product, [11.5, 4.0, 10.0]) print("Matrix-vector product:", product)
$ python3 sparse_array_create.py COO format: coo Shape: (3, 4) Stored coordinate entries: 5 CSR format: csr Stored positions after conversion: 4 Dense check: [[10. 0. 3. 0.] [ 0. 0. 8. 0.] [10. 0. 0. 0.]] Matrix-vector product: [11.5 4. 10. ]