{"record":{"id":"5db1919582a866cd","repo":"pandas-dev/pandas","slug":"dtype-type-does-not-support-how-operations","errorCode":null,"errorMessage":"{dtype} type does not support {how} operations","messagePattern":"(.+?) type does not support (.+?) operations","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/categorical.py","lineNumber":2871,"sourceCode":"\n    def _groupby_op(\n        self,\n        *,\n        how: str,\n        has_dropped_na: bool,\n        min_count: int,\n        ngroups: int,\n        ids: npt.NDArray[np.intp],\n        **kwargs,\n    ):\n        from pandas.core.groupby.ops import WrappedCythonOp\n\n        kind = WrappedCythonOp.get_kind_from_how(how)\n        op = WrappedCythonOp(how=how, kind=kind, has_dropped_na=has_dropped_na)\n\n        dtype = self.dtype\n        if how in [\"sum\", \"prod\", \"cumsum\", \"cumprod\", \"skew\", \"kurt\"]:\n            raise TypeError(f\"{dtype} type does not support {how} operations\")\n        if how in [\"min\", \"max\", \"rank\", \"idxmin\", \"idxmax\"] and not dtype.ordered:\n            # raise TypeError instead of NotImplementedError to ensure we\n            #  don't go down a group-by-group path, since in the empty-groups\n            #  case that would fail to raise\n            raise TypeError(f\"Cannot perform {how} with non-ordered Categorical\")\n        if how not in [\n            \"rank\",\n            \"any\",\n            \"all\",\n            \"first\",\n            \"last\",\n            \"min\",\n            \"max\",\n            \"idxmin\",\n            \"idxmax\",\n        ]:\n            if kind == \"transform\":\n                raise TypeError(f\"{dtype} type does not support {how} operations\")","sourceCodeStart":2853,"sourceCodeEnd":2889,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/categorical.py#L2853-L2889","documentation":"Raised by Categorical._groupby_op when the groupby aggregation 'how' is one of sum, prod, cumsum, cumprod, skew, or kurt. Arithmetic aggregations are undefined on category labels (they have no magnitude), so pandas rejects them up front before any computation. This is a hard type contract: categorical supports order and boolean aggregations only.","triggerScenarios":"df.groupby('g')['cat_col'].sum(), .prod(), .cumsum(), .cumprod(), .skew(), or .kurt() on a categorical-typed column.","commonSituations":"Blindly running df.groupby(...).agg(['sum','mean','min','max']) across all columns including object-like category columns; or a column that should be numeric but was inferred as category because it had few unique values.","solutions":["Cast the column to its numeric value dtype before aggregating: df['cat_col'].astype(df['cat_col'].cat.categories.dtype).","Drop arithmetic aggregations from the agg spec for categorical columns.","Confirm the column should be categorical; if not, leave it as numeric and skip dtype='category'."],"exampleFix":"// before\ndf.groupby('g')['cat'].sum()  # TypeError: category type does not support sum\n\n// after\ndf.groupby('g')['cat'].astype('int64').sum()  # if categories are numeric\n# or use a valid aggregation\ndf.groupby('g')['cat'].first()","handlingStrategy":"type-guard","validationCode":"ARITH_HOW = {'sum','prod','cumsum','cumprod','skew','kurt'}\ndef safe_groupby_agg(s, how):\n    import pandas as pd\n    if isinstance(s.dtype, pd.CategoricalDtype) and how in ARITH_HOW:\n        raise TypeError(f'{how} undefined on Categorical; cast to numeric first')\n    return getattr(s, how)()","typeGuard":"import pandas as pd\nfrom typing import Any\n\ndef supports_groupby_how(obj: Any, how: str) -> bool:\n    if isinstance(getattr(obj, 'dtype', None), pd.CategoricalDtype):\n        return how not in {'sum','prod','cumsum','cumprod','skew','kurt'}\n    return True","tryCatchPattern":"try:\n    df.groupby('g')['cat'].sum()\nexcept TypeError as e:\n    if 'does not support' in str(e) and 'operations' in str(e):\n        df['cat'].astype('int64').groupby(df['g']).sum()\n    else:\n        raise","preventionTips":["Filter arithmetic aggregations out of categorical columns in agg specs.","Cast category columns to numeric values when arithmetic is needed."],"tags":["categorical","groupby","aggregation"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}