{"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/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/categorical.py#L2853-L2889","documentation":"Raised in Categorical._groupby_op when the aggregation how is one of sum, prod, cumsum, cumprod, skew, or kurt. These are arithmetic/statistical operations that are undefined for category-typed data regardless of whether the categorical is ordered. The error fires before any ordered check because arithmetic simply has no meaning on category codes-as-labels.","triggerScenarios":"df.groupby('g')['catcol'].sum(), .prod(), .cumsum(), .cumprod(), .skew(), .kurt(). df.groupby('g').agg({'catcol': 'sum'}). Resample/rolling reductions that route through _groupby_op with how='sum'.","commonSituations":"User groups by one categorical and tries to sum another categorical column. Calling df.sum() on a frame that contains a categorical column (sum dispatched column-wise). agg('sum') on mixed-type frames where one column is categorical.","solutions":["Exclude categorical columns from arithmetic aggregations: select_dtypes(exclude='category').","If the categorical holds numeric categories and you want numeric sum, cast first: df['col'].astype('int64') then group.","Switch to a categorical-appropriate aggregation: count, size, first, last, or value_counts.","Use observed=True and aggregate only on numeric columns alongside the grouping categorical."],"exampleFix":"# before\ndf = pd.DataFrame({'g': ['x','y'], 'c': pd.Categorical([1,2])})\ndf.groupby('g')['c'].sum()  # TypeError\n\n# after\ndf['c_num'] = df['c'].astype('int64')\ndf.groupby('g')['c_num'].sum()","handlingStrategy":"validation","validationCode":"how = 'sum'\narithmetic_hows = {'sum','prod','cumsum','cumprod','skew','kurt'}\ncols = [c for c in df.columns if not (isinstance(df[c].dtype, pd.CategoricalDtype) and how in arithmetic_hows)]\ndf.groupby('g')[cols].agg(how)","typeGuard":"def aggregation_supported_for_categorical(how: str) -> bool:\n    return how not in {'sum','prod','cumsum','cumprod','skew','kurt'}","tryCatchPattern":"try:\n    df.groupby('g')['catcol'].sum()\nexcept TypeError as e:\n    if 'does not support' in str(e):\n        df.groupby('g')['catcol'].astype('int64').sum()\n    else:\n        raise","preventionTips":["Select numeric columns before arithmetic groupby: df.select_dtypes(include='number').","Maintain a dtype allowlist for aggregation pipelines."],"tags":["categorical","groupby","aggregation","sum"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}