The .data attribute, together with the matrix's .indices and .indptr arrays, forms the complete internal representation of a CSR matrix — .data holds just the nonzero values themselves, in the same order they're stored internally, row by row, while .indices and .indptr encode exactly where each of those values belongs in the full matrix. Directly inspecting .data is a quick way to see, and even modify, the actual stored numeric values without needing to reconstruct the full dense matrix first.
1Understanding csr_matrix.data
The .data attribute, together with the matrix's .indices and .indptr arrays, forms the complete internal representation of a CSR matrix — .data holds just the nonzero values themselves, in the same order they're stored internally, row by row, while .indices and .indptr encode exactly where each of those values belongs in the full matrix. Directly inspecting .data is a quick way to see, and even modify, the actual stored numeric values without needing to reconstruct the full dense matrix first.
Modifying csr_matrix.data directly changes the matrix's existing nonzero values in place efficiently, without needing to convert to a dense array first — but it can't be used to introduce brand-new nonzero entries at previously-zero positions, since that would require also updating the .indices/.indptr structure.
from scipy import sparse
import numpy as np
dense = np.array([[0, 0, 3], [4, 0, 0], [0, 5, 0]])
sparse_matrix = sparse.csr_matrix(dense)
print(sparse_matrix.data)2Practical Example
Here is a real-world application of csr_matrix.data showing how it is used in production SciPy code.
from scipy import sparse
import numpy as np
dense = np.array([[0, 2], [3, 0]])
sparse_matrix = sparse.csr_matrix(dense)
sparse_matrix.data *= 10
print(sparse_matrix.toarray())3Best Practices
Follow these guidelines when working with csr_matrix.data:
1. Inspect .data directly when you need to quickly see or process just the actual nonzero values, without the overhead of converting to a dense array first
2. Modify existing nonzero values directly through .data for an efficient in-place update, rather than converting to dense, modifying, and converting back
3. Use proper indexing/assignment on the sparse matrix itself, not direct .data manipulation, when you need to introduce a genuinely new nonzero entry at a previously-zero position
Tip: Modifying csr_matrix.data directly changes the matrix's existing nonzero values in place efficiently, without needing to convert to a dense array first — but it can't be used to introduce brand-new nonzero entries at previously-zero positions, since that would require also updating the .indices/.indptr structure.
from scipy import sparse
import numpy as np
dense = np.array([[0, 0, 3], [4, 0, 0], [0, 5, 0]])
sparse_matrix = sparse.csr_matrix(dense)
print(sparse_matrix.data)