Introduction
Sparse data handling helps us work efficiently with data that has many empty or zero values. It saves memory and speeds up calculations.
Sparse data handling helps us work efficiently with data that has many empty or zero values. It saves memory and speeds up calculations.
from scipy.sparse import csr_matrix # Create a sparse matrix from a dense 2D list or array sparse_matrix = csr_matrix(dense_data)
csr_matrix from scipy.sparse to create a compressed sparse row matrix.from scipy.sparse import csr_matrix dense_data = [[0, 0, 1], [1, 0, 0], [0, 0, 0]] sparse_matrix = csr_matrix(dense_data) print(sparse_matrix)
print(sparse_matrix.toarray())This program shows how to convert a dense matrix with many zeros into a sparse matrix, then back to dense. It also prints the internal sparse data arrays.
from scipy.sparse import csr_matrix import numpy as np # Example dense data with many zeros ratings = np.array([ [0, 0, 5, 0], [4, 0, 0, 0], [0, 3, 0, 0], [0, 0, 0, 0] ]) # Convert dense data to sparse format sparse_ratings = csr_matrix(ratings) # Print sparse matrix info print('Sparse matrix data:', sparse_ratings.data) print('Sparse matrix indices:', sparse_ratings.indices) print('Sparse matrix indptr:', sparse_ratings.indptr) # Convert back to dense to verify print('Dense matrix from sparse:') print(sparse_ratings.toarray())
Sparse matrices save memory but some operations are slower than with dense arrays.
Use sparse data structures when zeros dominate your data to improve performance.
Sparse data handling stores only important non-zero values.
It is useful for large datasets with many zeros or missing values.
Use scipy.sparse to create and work with sparse matrices in Python.
import scipy.sparse as sp to use sparse matrix functions.import numpy as np from scipy.sparse import csr_matrix arr = np.array([[0, 0, 1], [1, 0, 0], [0, 1, 0]]) sparse_mat = csr_matrix(arr) print(sparse_mat.nnz)
csr_matrix stores only non-zero elements. The nnz attribute counts these non-zero values, which is 3.from scipy.sparse import csr_matrix matrix = csr_matrix([1, 0, 0, 2, 0, 3]) print(matrix.shape)
csr_matrix expects a 2D array or matrix-like input, but a 1D list is given.csr_matrix is efficient for large sparse data and supports easy conversion back to dense..toarray() method on the sparse matrix to get the original dense NumPy array without data loss.csr_matrix to convert, then .toarray() to convert back -> Option BPass the test and this pattern moves unknown