Build from row, column, and value arrays
Assembling sparse data from indexed observations
SciPy · Class
Constructs a sparse matrix in coordinate (COO), also called ijv or triplet, format. It accepts dense or sparse input, an empty shape, or value arrays paired with row and column indices.
A COO matrix stores each supplied value alongside its row and column index. Create one from coordinate arrays, optionally specify its shape and dtype, and convert it to another sparse format for operations that require a different representation.
scipy.sparse.coo_matrix(arg1, shape=None, dtype=None, copy=False)| Name | Type | Description |
|---|---|---|
arg1 | array-like, sparse matrix, tuple, or coordinate tuple | Input object, shape tuple, or coordinate data used to construct the matrix. |
shape | 2-tuple of ints, optional | Optional matrix dimensions; for coordinate input, written as (M, N). |
dtype | dtype, optional | Optional data type; empty matrices default to dtype='d'. |
copy | bool, optional | Whether to copy input data when applicable. |
A sparse matrix in COO format.
import numpy as np
from scipy.sparse import coo_matrix
row = np.array([0, 1, 1])
col = np.array([0, 1, 2])
data = np.array([4, 5, 6])
A = coo_matrix((data, (row, col)), shape=(2, 3))
print(A.toarray())
Builds a 2-by-3 COO matrix from values and their row and column coordinates, then converts it to a dense array for display.
Assembling sparse data from indexed observations
Converting an existing dense or sparse matrix
Preparing sparse data before changing formats
The constructor represents a sparse matrix in coordinate, or triplet, format. With data, row indices, and column indices, each value is placed according to A[i[k], j[k]] = data[k].
Follow-up: How can an empty matrix be created? Use coo_matrix((M, N), dtype=...) with the desired dimensions and optional dtype.
The constructor accepts a dense matrix, another sparse matrix, a shape tuple for an empty matrix, or coordinate data. The coordinate form uses coo_matrix((data, (i, j)), shape=(M, N)).
Follow-up: What happens when shape is omitted for coordinate data? The shape is inferred from the index arrays.
COO supports sparse arithmetic such as addition, subtraction, multiplication, division, and matrix power. Its coordinate representation is also useful when assembling entries from indexed data.
Follow-up: Which representation should be used when indexed access or efficient arithmetic in a particular operation is required? Convert the COO object to the appropriate sparse format using its conversion methods.
scipy.sparse.coo_arrayscipy.sparse.csr_matrixscipy.sparse.csc_matrixscipy.sparse.dok_matrixscipy.sparse.lil_matrix