{"record":{"id":"9ac0ec49ddb907fe","repo":"pandas-dev/pandas","slug":"can-only-use-the-sparse-accessor-with-sparse-da","errorCode":null,"errorMessage":"Can only use the '.sparse' accessor with Sparse data.","messagePattern":"Can only use the '\\.sparse' accessor with Sparse data\\.","errorType":"exception","errorClass":"AttributeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/sparse/accessor.py","lineNumber":78,"sourceCode":"    See Also\n    --------\n    Series.sparse.to_coo : Create a scipy.sparse.coo_matrix from a Series with\n        MultiIndex.\n    Series.sparse.from_coo : Create a Series with sparse values from a\n        scipy.sparse.coo_matrix.\n\n    Examples\n    --------\n    >>> ser = pd.Series([0, 0, 2, 2, 2], dtype=\"Sparse[int]\")\n    >>> ser.sparse.density\n    0.6\n    >>> ser.sparse.sp_values\n    array([2, 2, 2])\n    \"\"\"\n\n    def _validate(self, data) -> None:\n        if not isinstance(data.dtype, SparseDtype):\n            raise AttributeError(self._validation_msg)\n\n    def _delegate_property_get(self, name: str, *args, **kwargs):\n        return getattr(self._parent.array, name)\n\n    def _delegate_method(self, name: str, *args, **kwargs):\n        if name == \"from_coo\":\n            return self.from_coo(*args, **kwargs)\n        elif name == \"to_coo\":\n            return self.to_coo(*args, **kwargs)\n        else:\n            raise ValueError\n\n    @classmethod\n    def from_coo(cls, A, dense_index: bool = False) -> Series:\n        \"\"\"\n        Create a Series with sparse values from a scipy.sparse.coo_matrix.\n\n        This method takes a ``scipy.sparse.coo_matrix`` (coordinate format) as input and","sourceCodeStart":60,"sourceCodeEnd":96,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/sparse/accessor.py#L60-L96","documentation":"Raised by SparseAccessor._validate when the `.sparse` accessor is used on a Series whose dtype is not a SparseDtype. Accessors are registered only for sparse-backed Series, so accessing `.sparse` on a regular dense Series is a programming error rather than a missing attribute.","triggerScenarios":"pd.Series([1,2,3]).sparse.density; pd.Series([0,0,1]).astype('int64').sparse; a Series that was sparse but got densified by an operation (e.g. .astype('float64')).","commonSituations":"Forgetting dtype='Sparse[int]' when constructing the Series; an intermediate op (groupby/merge/astype) silently converting SparseArray to a dense ndarray; loading data without specifying sparse dtype.","solutions":["Construct with an explicit sparse dtype: pd.Series([...], dtype='Sparse[int]').","Convert an existing dense Series: s.astype('Sparse[int]').","Check before accessing: if isinstance(s.dtype, pd.SparseDtype): ... else: use the dense path."],"exampleFix":"// before\ndensity = pd.Series([0,0,1,2]).sparse.density\n// after\ndensity = pd.Series([0,0,1,2], dtype='Sparse[int]').sparse.density","handlingStrategy":"type-guard","validationCode":"import pandas as pd\n\ndef sparse_density(s):\n    if not isinstance(s.dtype, pd.SparseDtype):\n        s = s.astype('Sparse[int]')\n    return s.sparse.density","typeGuard":"def is_sparse_series(s) -> bool:\n    import pandas as pd\n    return isinstance(s.dtype, pd.SparseDtype)","tryCatchPattern":"try:\n    return s.sparse.density\nexcept AttributeError as e:\n    if 'sparse accessor' in str(e):\n        return s.astype('Sparse[int]').sparse.density\n    raise","preventionTips":["Construct sparse Series with dtype='Sparse[...]'.","Re-cast to sparse after ops that densify (astype/merge/groupby).","Guard accessor use with isinstance(dtype, SparseDtype)."],"tags":["pandas","sparse","accessor","dtype-validation"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}