{"record":{"id":"43897734f5ef944c","repo":"pandas-dev/pandas","slug":"cannot-perform-name-with-type-self-dtype-438977","errorCode":null,"errorMessage":"cannot perform {name} with type {self.dtype}","messagePattern":"cannot perform (.+?) with type (.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/sparse/array.py","lineNumber":1605,"sourceCode":"            self.__dict__.update(state)\n\n    def nonzero(self) -> tuple[npt.NDArray[np.int32]]:\n        if self.fill_value == 0:\n            return (self.sp_index.indices,)\n        else:\n            return (self.sp_index.indices[self.sp_values != 0],)\n\n    # ------------------------------------------------------------------------\n    # Reductions\n    # ------------------------------------------------------------------------\n\n    def _reduce(\n        self, name: str, *, skipna: bool = True, keepdims: bool = False, **kwargs\n    ):\n        method = getattr(self, name, None)\n\n        if method is None:\n            raise TypeError(f\"cannot perform {name} with type {self.dtype}\")\n\n        if name in (\"mean\", \"sum\", \"min\", \"max\"):\n            # these methods handle skipna themselves; dropping NAs beforehand\n            # would hide the NA from their skipna=False short-circuit\n            result = method(skipna=skipna, **kwargs)\n        else:\n            if skipna:\n                arr = self\n            else:\n                arr = self.dropna()\n            result = getattr(arr, name)(**kwargs)\n\n        if keepdims:\n            return type(self)([result], dtype=self.dtype)\n        else:\n            return result\n\n    def all(self, axis=None, *args, **kwargs):","sourceCodeStart":1587,"sourceCodeEnd":1623,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/sparse/array.py#L1587-L1623","documentation":"TypeError from SparseArray._reduce when no method matching the reduction name exists on the SparseArray (e.g. 'median', 'prod' not implemented). The reduction dispatcher (used by Series.describe/agg/reduce) only forwards names that the ExtensionArray exposes.","triggerScenarios":"pd.Series(sparse_arr).agg('median'); df.sparse_col.mean() works but df.sparse_col.prod() may not; calling arr._reduce('skew').","commonSituations":"Aggregating sparse columns with reduction names pandas does not implement for SparseArray; generic agg over a list of reductions where some are unsupported.","solutions":["Reduce on the dense equivalent: getattr(np.asarray(arr), name)() or pd.Series(np.asarray(arr)).agg(name).","Filter the reduction list to those SparseArray supports (sum, min, max, mean, etc.).","Register a custom reduction via ExtensionArray if you need sparse-aware behavior."],"exampleFix":"// before\npd.Series(arr).agg('median')  # raises for unsupported name\n// after\npd.Series(np.asarray(arr)).agg('median')","handlingStrategy":"validation","validationCode":"SPARSE_REDUCTIONS = {'sum', 'min', 'max', 'mean', 'prod'}\ndef safe_reduce(arr, name, **kw):\n    if hasattr(arr, name):\n        return getattr(arr, name)(**kw)\n    import numpy as np\n    return getattr(np.asarray(arr), name)(**kw)","typeGuard":"def sparse_supports_reduction(arr, name) -> bool:\n    return hasattr(arr, name)","tryCatchPattern":"try:\n    pd.Series(arr).agg(name)\nexcept TypeError as e:\n    if 'cannot perform' in str(e):\n        import numpy as np\n        out = getattr(np.asarray(arr), name)()\n    else:\n        raise","preventionTips":["Reduce unsupported aggregations on dense materialization.","Filter agg lists to SparseArray-supported names.","Test custom reductions against sparse-backed Series."],"tags":["sparse","reduce","aggregation","extension-array"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}