pandas-dev/pandas · error · TypeError
type does not support operations
Error message
{dtype} type does not support {how} operations What it means
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.
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.
Example fix
# before
df = pd.DataFrame({'g': ['x','y'], 'c': pd.Categorical([1,2])})
df.groupby('g')['c'].sum() # TypeError
# after
df['c_num'] = df['c'].astype('int64')
df.groupby('g')['c_num'].sum() Defensive patterns
Strategy: validation
Validate before calling
how = 'sum'
arithmetic_hows = {'sum','prod','cumsum','cumprod','skew','kurt'}
cols = [c for c in df.columns if not (isinstance(df[c].dtype, pd.CategoricalDtype) and how in arithmetic_hows)]
df.groupby('g')[cols].agg(how) Type guard
def aggregation_supported_for_categorical(how: str) -> bool:
return how not in {'sum','prod','cumsum','cumprod','skew','kurt'} Try / catch
try:
df.groupby('g')['catcol'].sum()
except TypeError as e:
if 'does not support' in str(e):
df.groupby('g')['catcol'].astype('int64').sum()
else:
raise Prevention
- Select numeric columns before arithmetic groupby: df.select_dtypes(include='number').
- Maintain a dtype allowlist for aggregation pipelines.
When it happens
Trigger: 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'.
Common situations: 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.
Related errors
- Cannot perform with non-ordered Categorical
- datetime64 type does not support operation
- > 1 ndim Categorical are not supported at this time
- Accumulation not supported for
- axis is out of bounds for array of dimension
AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11).
Data as JSON: /api/errors/5db1919582a866cd.
Report an issue: GitHub.
Appendix: 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 3b7651241d)