pandas-dev/pandas · error · TypeError
Expected coo_matrix. Got {type(A).__name__} instead.
Error message
Expected coo_matrix. Got {type(A).__name__} instead. What it means
Raised by coo_to_sparse_series when the input lacks the .data/.row/.col attributes of a scipy.sparse.coo_matrix. The function wraps the attribute access in a try/except AttributeError and re-raises as TypeError so callers get a clear contract violation instead of a confusing AttributeError. Only scipy.sparse.coo_matrix is accepted because the conversion logic reads A.data, A.row, and A.col directly.
Source
Thrown at pandas/core/arrays/sparse/scipy_sparse.py:200
Parameters
----------
A : scipy.sparse.coo_matrix
dense_index : bool, default False
Returns
-------
Series
Raises
------
TypeError if A is not a coo_matrix
"""
from pandas import SparseDtype
try:
ser = Series(A.data, MultiIndex.from_arrays((A.row, A.col)), copy=False)
except AttributeError as err:
raise TypeError(
f"Expected coo_matrix. Got {type(A).__name__} instead."
) from err
ser = ser.sort_index()
ser = ser.astype(SparseDtype(ser.dtype))
if dense_index:
ind = MultiIndex.from_product([A.row, A.col])
ser = ser.reindex(ind)
return ser
View on GitHub (pinned to 71959b8cb9)
Solutions
- Convert the matrix to coo format before calling: coo_to_sparse_series(A.tocoo()).
- Check the format up front: if A.format != 'coo': A = A.tocoo().
- Use scipy.sparse.coo_matrix directly when constructing data destined for pandas sparse Series.
Example fix
// before from pandas.core.arrays.sparse.scipy_sparse import coo_to_sparse_series series = coo_to_sparse_series(csr_mat) // after series = coo_to_sparse_series(csr_mat.tocoo())
Defensive patterns
Strategy: validation
Validate before calling
import scipy.sparse
def to_sparse_series(A):
if not (scipy.sparse.issparse(A) and A.format == 'coo'):
A = A.tocoo()
return coo_to_sparse_series(A) Type guard
import scipy.sparse
def is_coo_matrix(A) -> bool:
return scipy.sparse.issparse(A) and getattr(A, 'format', None) == 'coo' Prevention
- Always call .tocoo() on sparse matrices before passing to coo_to_sparse_series.
- Check A.format == 'coo' at trust boundaries in generic conversion utilities.
- Document the coo_matrix requirement in wrapper functions.
When it happens
Trigger: Calling pandas.core.arrays.sparse.scipy_sparse.coo_to_sparse_series with a csr_matrix, csc_matrix, lil_matrix, dok_matrix, a dense numpy.ndarray, a list, or any object that is not a scipy.sparse.coo_matrix. Also triggered indirectly through SparseDtype round-trips that pass the wrong sparse format.
Common situations: User obtains a csr_matrix from scikit-learn or scipy and tries to convert it to a pandas SparseSeries without converting format first. Copy-pasting code that worked on coo output but now feeds in a different sparse format.
Related errors
- Column length mismatch: {len(columns)} vs. {K}
- Index length mismatch: {len(index)} vs. {N}
- Cannot construct {type(self).__name__} from scalar data. Pas
- 'data' must have a single column, not '{ncol}'
- {func_name} requires a Series, Index, ExtensionArray, np.nda
AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07).
Data as JSON: /api/errors/15cd2fb01d183d4d.
Report an issue: GitHub.