Create A Sparse Matrix


# Load libraries
import numpy as np
from scipy import sparse

Create Dense Matrix

# Create a matrix
matrix = np.array([[0, 0],
                   [0, 1],
                   [3, 0]])

Convert To Sparse Matrix

# Create compressed sparse row (CSR) matrix
matrix_sparse = sparse.csr_matrix(matrix)

Note: There are many types of sparse matrices. In the example above we use CSR but the type we use should reflect our use case.