How to create a sparse array with SciPy

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.

Steps to create a SciPy sparse array:

  1. Create sparse_array_create.py with the coordinate data for a three-row array.
    sparse_array_create.py
    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.

  2. Append the COO construction and structural checks to sparse_array_create.py.
    coo = coo_array((values, (row, col)), shape=(3, 4))
    print("COO format:", coo.format)
    print("Shape:", coo.shape)
    print("Stored coordinate entries:", coo.nnz)
  3. Run the partial script to inspect the coordinate representation.
    $ python3 sparse_array_create.py
    COO format: coo
    Shape: (3, 4)
    Stored coordinate entries: 5
  4. Append the CSR conversion and small dense inspection to sparse_array_create.py.
    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.

  5. Append the validated matrix-vector calculation to sparse_array_create.py.
    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)
  6. Run the completed script to confirm coordinate consolidation and sparse multiplication.
    $ 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. ]