Learn Before
Code

Creating Sparse Matrices

A sparse matrix stores only its nonzero entries, saving memory when most elements are zero. Using NumPy together with SciPy's scipy.sparse module:

from scipy import sparse import numpy as np F = np.eye(3, k=1) # 3x3 matrix with ones on the first superdiagonal G = np.mat(np.identity(2)) # 2x2 identity matrix C[C > 0.5] = 0 # Zero out entries so the array becomes sparse H = sparse.csr_matrix(C) # Compressed Sparse Row (CSR) matrix I = sparse.csc_matrix(D) # Compressed Sparse Column (CSC) matrix J = sparse.dok_matrix(A) # Dictionary Of Keys (DOK) matrix E.todense() # Convert a sparse matrix back to a dense (full) matrix sparse.isspmatrix_csc(A) # Check whether a matrix is stored in CSC format

0

1

Updated 2026-07-20

Tags

Python Programming Language

Data Science