pandas-dev/pandas · error · TypeError
{dtype} type does not support {how} operations
Error message
{dtype} type does not support {how} operations What it means
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.
Source
Thrown at pandas/core/arrays/categorical.py:2871
def _groupby_op(
self,
*,
how: str,
has_dropped_na: bool,
min_count: int,
ngroups: int,
ids: npt.NDArray[np.intp],
**kwargs,
):
from pandas.core.groupby.ops import WrappedCythonOp
kind = WrappedCythonOp.get_kind_from_how(how)
op = WrappedCythonOp(how=how, kind=kind, has_dropped_na=has_dropped_na)
dtype = self.dtype
if how in ["sum", "prod", "cumsum", "cumprod", "skew", "kurt"]:
raise TypeError(f"{dtype} type does not support {how} operations")
if how in ["min", "max", "rank", "idxmin", "idxmax"] and not dtype.ordered:
# raise TypeError instead of NotImplementedError to ensure we
# don't go down a group-by-group path, since in the empty-groups
# case that would fail to raise
raise TypeError(f"Cannot perform {how} with non-ordered Categorical")
if how not in [
"rank",
"any",
"all",
"first",
"last",
"min",
"max",
"idxmin",
"idxmax",
]:
if kind == "transform":
raise TypeError(f"{dtype} type does not support {how} operations")View on GitHub (pinned to 71959b8cb9)
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'.
Example fix
// before
df.groupby('g')['cat'].sum() # TypeError: category type does not support sum
// after
df.groupby('g')['cat'].astype('int64').sum() # if categories are numeric
# or use a valid aggregation
df.groupby('g')['cat'].first() Defensive patterns
Strategy: type-guard
Validate before calling
ARITH_HOW = {'sum','prod','cumsum','cumprod','skew','kurt'}
def safe_groupby_agg(s, how):
import pandas as pd
if isinstance(s.dtype, pd.CategoricalDtype) and how in ARITH_HOW:
raise TypeError(f'{how} undefined on Categorical; cast to numeric first')
return getattr(s, how)() Type guard
import pandas as pd
from typing import Any
def supports_groupby_how(obj: Any, how: str) -> bool:
if isinstance(getattr(obj, 'dtype', None), pd.CategoricalDtype):
return how not in {'sum','prod','cumsum','cumprod','skew','kurt'}
return True Try / catch
try:
df.groupby('g')['cat'].sum()
except TypeError as e:
if 'does not support' in str(e) and 'operations' in str(e):
df['cat'].astype('int64').groupby(df['g']).sum()
else:
raise Prevention
- Filter arithmetic aggregations out of categorical columns in agg specs.
- Cast category columns to numeric values when arithmetic is needed.
When it happens
Trigger: df.groupby('g')['cat_col'].sum(), .prod(), .cumsum(), .cumprod(), .skew(), or .kurt() on a categorical-typed column.
Common situations: 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.
Related errors
- numpy operations are not valid with groupby. Use .groupby(..
- dtype '{self.dtype}' does not support operation '{how}'
- dtype '{self.dtype}' does not support operation '{how}'
- Cannot perform {how} with non-ordered Categorical
- dtype '{self.dtype}' does not support operation 'quantile'
AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07).
Data as JSON: /api/errors/5db1919582a866cd.
Report an issue: GitHub.