Free tools Windows power users keep installed
One-click scans. No signup required.
scipy.sparse.csr_matrix stores a sparse two-dimensional matrix in Compressed Sparse Row form: each row’s nonzero entries are kept together, while a pointer array marks each row’s segment. This layout is a good fit for row access and matrix-vector calculations, but a poor choice for frequent column slicing or changes to which entries exist.
What a CSR matrix represents
A sparse matrix has many entries equal to zero, so storing every position can waste space and work. A CSR matrix stores its represented values and their column positions row by row rather than keeping a dense rectangular grid. SciPy describes csr_matrix as a “Compressed Sparse Row matrix.” See the SciPy csr_matrix reference.
As an Amazon Associate I earn from qualifying purchases.
CSR’s compactness does not mean every stored value is necessarily nonzero: explicitly stored zeros can remain in the arrays. The nnz attribute counts stored values, including those explicit zeros.
How the three arrays work
The representation consists of three arrays:
dataholds the stored values.indicesholds the column index for each corresponding value indata.indptrmarks the start and end of each row’s segment in the other two arrays.
For row i, its entries are found in data[indptr[i]:indptr[i+1]], and their column positions are in indices[indptr[i]:indptr[i+1]]. For example, if indptr[i] is 3 and indptr[i+1] is 5, that row has two stored entries at positions 3 and 4 of both arrays. The pointer array therefore has one more boundary than there are rows.
#1 Best Overall
Here is a small direct construction. The first row contains 4 in column 1, the second is empty, and the third contains 7 in column 0:
import numpy as np
from scipy.sparse import csr_matrix
matrix = csr_matrix(
(np.array([4, 7]), np.array([1, 0]), np.array([0, 1, 1, 2])),
shape=(3, 2),
)
# Row 0: columns [1], values [4]
# Row 1: no stored entries
# Row 2: columns [0], values [7]
The explicit shape makes the intended dimensions clear, including empty rows or trailing columns. When shape is omitted for the direct three-array constructor, SciPy infers dimensions from the index arrays; consult the constructor reference when relying on that behavior.
Ways to construct a CSR matrix
Choose a constructor based on the data you already have. SciPy’s API supports dense input, another sparse object, coordinates, and raw CSR arrays.
| Input you have | Construction pattern | When it is useful |
|---|---|---|
| Two-dimensional dense ndarray | csr_matrix(dense) |
Converting an existing dense matrix when its values are sparse enough to warrant sparse storage. |
| Another sparse matrix or sparse array | csr_matrix(sparse_object) |
Converting an existing sparse object to CSR for row-oriented work. |
| Desired dimensions, initially empty | csr_matrix((M, N), dtype=...) |
Creating a zero-filled sparse matrix of shape (M, N). |
| Coordinate arrays of rows, columns, and values | csr_matrix((data, (row_ind, col_ind)), shape=(M, N)) |
Assembling entries given as coordinates. |
| CSR’s three arrays | csr_matrix((data, indices, indptr), shape=(M, N)) |
Constructing directly when the row-compressed representation is already available. |
For example, coordinate input lets you describe entries by position without manually calculating row boundaries:
Rank #3
from scipy.sparse import csr_matrix
row = [0, 0, 2]
col = [0, 2, 1]
data = [1, 2, 3]
matrix = csr_matrix((data, (row, col)), shape=(3, 3))
If a coordinate appears more than once, SciPy sums the values at that position. In the official example, duplicate entries at (0, 0) with values 1 and 8 produce a stored value of 9. This is useful when separate contributions are accumulated as coordinate records, but it also means repeated coordinates do not remain separate matrix entries. See SciPy’s CSR examples and constructor details.
Building row by row
When assembling a term-document matrix or another naturally row-oriented dataset, append each row’s column indices and values, then append the cumulative count of stored entries to indptr. That final count marks the end of the row just completed and the beginning of the next. SciPy’s reference demonstrates this incremental pattern.
Rank #4
For general coordinate-based construction, SciPy recommends COO; DOK and LIL are also construction-friendly formats. The SciPy sparse arrays overview describes these format choices and conversions.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
What CSR is good at—and where it is not
| Workload | CSR fit | Alternative to consider |
|---|---|---|
| Row slicing | Efficient | — |
| Matrix-vector products | Fast | — |
| Sparse arithmetic | Supported efficiently for arithmetic such as addition, subtraction, multiplication, division, and matrix power | — |
| Column slicing | Slow | CSC, which is organized around columns |
| Changing the sparsity structure | Expensive | LIL or DOK while adding, removing, or changing which positions are stored |
| Creating entries from coordinates | Possible, though not the preferred construction format in SciPy’s guidance | COO for coordinate/value input; DOK or LIL are also recommended construction formats |
CSR is therefore most natural after the matrix structure is reasonably settled and the work reads rows or computes products. If the main operation is column-oriented, CSC has efficient column slicing but slow row slicing; see SciPy’s CSC reference. Conversions among CSR, CSC, and COO are documented as linear-time, so it is practical to build in a convenient format and convert for the computation that follows.
Best Value
Using CSR without accidentally densifying data
Use @ for matrix-vector multiplication with a sparse object, as shown in the SciPy sparse overview. Do not assume every NumPy function accepts sparse arrays meaningfully: check whether SciPy provides a sparse-aware operation, or deliberately convert to a dense array only when the matrix size makes that appropriate. Densifying a large sparse matrix can require memory for every position, including the zeros the sparse representation avoids storing.
Account for SciPy’s sparse matrix-to-array transition
The current csr_matrix reference warns: “SciPy sparse is shifting from a sparse matrix interface to a sparse array interface. In the next few releases we expect to deprecate the sparse matrix interface.” The warning does not specify a deprecation date. When maintaining code, review the current SciPy sparse migration guidance and verify how downstream libraries handle sparse arrays before changing an established matrix-based workflow.
The key distinction is the object’s interface, not the CSR storage principle: both matrix and array APIs are sparse formats, but code that accepts one should not be assumed to accept the other without checking its library’s support.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




