Memory-efficient sparse storage
Store matrices with many zeros while retaining column-oriented compressed storage.
SciPy · Class
scipy.sparse.csc_matrix creates compressed sparse column matrices. It accepts dense, sparse, coordinate-form, shape-only, and explicit compressed-storage inputs.
csc_matrix stores a sparse matrix by columns. In its standard representation, each column's row indices occupy a slice of indices selected by adjacent indptr values, while the corresponding numerical entries are in data; it can also be built from dense input, another sparse matrix, dimensions, coordinate triples, or these storage arrays.
scipy.sparse.csc_matrix(arg1, shape=None, dtype=None, copy=False)| Name | Type | Description |
|---|---|---|
arg1 | object | Constructor input: a 2-D ndarray, sparse array or matrix, shape tuple, coordinate-form tuple, or compressed-form tuple. |
shape | tuple[int, int] or None | Optional matrix shape, written as (M, N). |
dtype | dtype or None | Optional element data type; for an empty matrix it defaults to dtype='d'. |
copy | bool | Whether to copy input data when applicable. |
A scipy.sparse.csc_matrix object.
import numpy as np
from scipy.sparse import csc_matrix
A = csc_matrix(np.array([[1, 0, 2], [0, 3, 0]]))
print(A.toarray())
print(A.indptr)
print(A.indices)
print(A.data)Creates a CSC matrix from a two-dimensional NumPy array and inspects its dense form and three storage arrays.
Store matrices with many zeros while retaining column-oriented compressed storage.
Build a matrix from nonzero values and their row and column coordinates.
Construct or inspect explicit CSC arrays for interoperability with sparse algorithms.
It is a compressed sparse column matrix. Its compressed representation uses data for values, indices for row positions, and indptr to delimit each column's segment in the first two arrays.
Follow-up: How do you locate the stored entries of column j? Use indices[indptr[j]:indptr[j+1]] for row positions and data[indptr[j]:indptr[j+1]] for their values.
You can pass a two-dimensional ndarray, another sparse object, a shape tuple, coordinate-form data with row and column indices, or the compressed triple data, indices, indptr. The optional shape specifies matrix dimensions where needed.
Follow-up: What relationship must coordinate-form inputs satisfy? For each k, the entry at row_ind[k], col_ind[k] equals data[k].
For column i, row indices are stored in indices[indptr[i]:indptr[i+1]], and matching values are stored in data[indptr[i]:indptr[i+1]]. Thus indptr provides the boundaries for each column's compressed data.
Follow-up: How can you inspect or validate the representation? Compare each column's boundary slice in indices and data, and ensure indptr has the expected column boundary structure.
scipy.sparse.csr_matrixscipy.sparse.coo_matrixscipy.sparse.dia_matrixscipy.sparse.bsr_matrix