pandas-dev/pandas · error · TypeError

Cannot perform with non-ordered Categorical

Error message

Cannot perform {how} with non-ordered Categorical

What it means

Raised in Categorical._groupby_op when how is min, max, rank, idxmin, or idxmax and the categorical dtype is not ordered. Same rationale as error 240: these operations need a total order, which an unordered categorical does not provide. Raised as TypeError (not NotImplementedError) deliberately so the group-by-group fallback path is not taken.

Solutions

  1. Make the categorical ordered: df['col'] = df['col'].cat.as_ordered() (optionally set_categories in rank order first).
  2. If the category order is meaningful, define it: set_categories(['low','med','high'], ordered=True).
  3. Use count/size/first instead of min/max when ordering is genuinely absent.
  4. Separate categorical columns out of min/max aggregations.

Example fix

# before
df = pd.DataFrame({'g': ['x','x','y'], 'c': pd.Categorical(['b','a','c'])})
df.groupby('g')['c'].min()  # TypeError

# after
df['c'] = df['c'].cat.as_ordered()
df.groupby('g')['c'].min()
Defensive patterns

Strategy: validation

Validate before calling

how = 'min'
order_hows = {'min','max','rank','idxmin','idxmax'}
col = 'catcol'
if how in order_hows and isinstance(df[col].dtype, pd.CategoricalDtype) and not df[col].cat.ordered:
    df[col] = df[col].cat.as_ordered()
df.groupby('g')[col].agg(how)

Type guard

def groupby_min_ok(s: pd.Series) -> bool:
    return not (isinstance(s.dtype, pd.CategoricalDtype) and not s.cat.ordered)

Try / catch

try:
    df.groupby('g')['catcol'].min()
except TypeError as e:
    if 'non-ordered Categorical' in str(e):
        df['catcol'] = df['catcol'].cat.as_ordered()
        df.groupby('g')['catcol'].min()
    else:
        raise

Prevention

When it happens

Trigger: df.groupby('g')['catcol'].min() / .max() / .rank() / .idxmin() / .idxmax() on an unordered categorical. df.groupby('g').agg({'catcol': 'min'}). Resample min/max on a categorical value column.

Common situations: Categorical group key created without ordered=True; user then asks for the min category per group. Grouping survey Likert-scale data stored as unordered categorical and requesting max. Multi-column agg where one categorical column receives a min/max spec.

Related errors


AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11). Data as JSON: /api/errors/2b2861f2abc1a5ec. Report an issue: GitHub.

Appendix: source

Thrown at pandas/core/arrays/categorical.py:2876

        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")
            raise TypeError(f"{dtype} dtype does not support aggregation '{how}'")

        result_mask = None
        mask = self.isna()
        if how == "rank":

View on GitHub (pinned to 3b7651241d)