Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk4 min

Understand SciPy’s CSR Matrix

SciPy’s CSR format stores sparse values row by row. Learn how data, indices, and indptr work, how to construct a CSR matrix, and when another sparse format fits better.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How the three arrays work

The representation consists of three arrays:

  • data holds the stored values.
  • indices holds the column index for each corresponding value in data.
  • indptr marks 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.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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:

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.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.