COO format stores three parallel arrays: the nonzero data values, and their corresponding row and column indices, with no particular ordering requirement and no restriction against duplicate (row, col) entries, which are automatically summed together when the matrix is used or converted. This makes COO the easiest sparse format to build up incrementally, especially when adding entries in an arbitrary, non-sorted order, but it doesn't support efficient direct arithmetic or slicing the way CSR/CSC do, which is why COO matrices are typically converted to CSR or CSC before being used in actual computations.
1Understanding sparse.coo_matrix()
COO format stores three parallel arrays: the nonzero data values, and their corresponding row and column indices, with no particular ordering requirement and no restriction against duplicate (row, col) entries, which are automatically summed together when the matrix is used or converted. This makes COO the easiest sparse format to build up incrementally, especially when adding entries in an arbitrary, non-sorted order, but it doesn't support efficient direct arithmetic or slicing the way CSR/CSC do, which is why COO matrices are typically converted to CSR or CSC before being used in actual computations.
Build a sparse matrix in COO format when constructing it from scratch, especially from separate lists of row indices, column indices, and values, then convert it to CSR or CSC with .tocsr()/.tocsc() before doing any actual arithmetic or slicing with it.
from scipy import sparse
row = [0, 1, 2]
col = [2, 0, 1]
data = [3, 4, 5]
matrix = sparse.coo_matrix((data, (row, col)), shape=(3, 3))
print(matrix.toarray())2Practical Example
Here is a real-world application of sparse.coo_matrix() showing how it is used in production SciPy code.
from scipy import sparse
row = [0, 0, 1]
col = [1, 1, 0]
data = [2, 3, 4]
matrix = sparse.coo_matrix((data, (row, col)), shape=(2, 2))
print(matrix.toarray())3Best Practices
Follow these guidelines when working with sparse.coo_matrix():
1. Use COO format specifically for initial construction of a sparse matrix, especially from three parallel arrays of row indices, column indices, and values
2. Convert a COO matrix to CSR or CSC with .tocsr()/.tocsc() before performing arithmetic or slicing, since COO itself doesn't support those operations efficiently
3. Take advantage of COO's automatic summing of duplicate (row, col) entries when building a matrix that naturally accumulates values at the same position, like a co-occurrence count matrix
Tip: Build a sparse matrix in COO format when constructing it from scratch, especially from separate lists of row indices, column indices, and values, then convert it to CSR or CSC with .tocsr()/.tocsc() before doing any actual arithmetic or slicing with it.
from scipy import sparse
row = [0, 1, 2]
col = [2, 0, 1]
data = [3, 4, 5]
matrix = sparse.coo_matrix((data, (row, col)), shape=(3, 3))
print(matrix.toarray())