pandas-dev/pandas · error · AttributeError
Can only use the '.sparse' accessor with Sparse data.
Error message
Can only use the '.sparse' accessor with Sparse data.
What it means
Raised as AttributeError by SparseArrayAccessor (Series.sparse) _validate when the Series dtype is not SparseDtype. The .sparse accessor is registered only for sparse-backed Series; accessing it on a dense Series is a programming error.
Solutions
- Cast first: ser.astype('Sparse[int]') (or 'Sparse[float64, 0.0]') before using .sparse.
- Check pd.api.types.is_sparse_dtype(ser.dtype) before accessing .sparse.
- Preserve sparse dtype end-to-end in your pipeline.
Example fix
# before s = pd.Series([0,0,1,2]) s.sparse.density # after s = pd.Series([0,0,1,2], dtype='Sparse[int]') s.sparse.density
Defensive patterns
Strategy: type-guard
Validate before calling
from pandas.api.types import is_sparse_dtype
def is_sparse_series(s) -> bool:
return is_sparse_dtype(s.dtype) Type guard
from pandas.api.types import is_sparse_dtype
def has_sparse_accessor(s) -> bool:
return is_sparse_dtype(getattr(s, 'dtype', None)) Try / catch
try:
val = s.sparse.density
except AttributeError as e:
if 'sparse accessor' in str(e):
val = s.astype('Sparse[float64]').sparse.density
else:
raise Prevention
- Construct sparse Series with dtype='Sparse[...]' from the start.
- Guard with pd.api.types.is_sparse_dtype(s.dtype) before .sparse.*.
- Watch for .astype() / .values calls that drop the sparse dtype.
When it happens
Trigger: ser.sparse.density where ser = pd.Series([0,0,1]); any df['col'].sparse.* on a column cast back to dense; calling .sparse.from_coo on a non-sparse Series.
Common situations: Forgetting to cast dtype='Sparse[int]' or dtype='Sparse[float]'; downstream code that re-cast a sparse column to dense via .astype() or .values; chained operations that lost the dtype.
Related errors
- ArrowStringArray requires a PyArrow (chunked) array of…
- bad operand type for unary +
- bins argument only works with numeric data.
- Can only use .cat accessor with a 'category' dtype
- Cannot construct from scalar data. Pass a sequence instead.
AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11).
Data as JSON: /api/errors/9ac0ec49ddb907fe.
Report an issue: GitHub.
Appendix: source
Thrown at pandas/core/arrays/sparse/accessor.py:78
See Also
--------
Series.sparse.to_coo : Create a scipy.sparse.coo_matrix from a Series with
MultiIndex.
Series.sparse.from_coo : Create a Series with sparse values from a
scipy.sparse.coo_matrix.
Examples
--------
>>> ser = pd.Series([0, 0, 2, 2, 2], dtype="Sparse[int]")
>>> ser.sparse.density
0.6
>>> ser.sparse.sp_values
array([2, 2, 2])
"""
def _validate(self, data) -> None:
if not isinstance(data.dtype, SparseDtype):
raise AttributeError(self._validation_msg)
def _delegate_property_get(self, name: str, *args, **kwargs):
return getattr(self._parent.array, name)
def _delegate_method(self, name: str, *args, **kwargs):
if name == "from_coo":
return self.from_coo(*args, **kwargs)
elif name == "to_coo":
return self.to_coo(*args, **kwargs)
else:
raise ValueError
@classmethod
def from_coo(cls, A, dense_index: bool = False) -> Series:
"""
Create a Series with sparse values from a scipy.sparse.coo_matrix.
This method takes a ``scipy.sparse.coo_matrix`` (coordinate format) as input andView on GitHub (pinned to 3b7651241d)