pandas-dev/pandas · error · TypeError

dtype ' ' does not support operation

Error message

dtype '{self.dtype}' does not support operation '{how}'

What it means

In _grouped_reduce, when the array's dtype is a StringDtype, the code explicitly rejects arithmetic/statistical groupby operations that are meaningless on strings (prod, mean, median, cumsum, cumprod, std, sem, var, skew, kurt) by raising TypeError. Only any/all/sum/first/last (and count) are permitted on string columns. This fails early to avoid a silent object-dtype conversion.

Solutions

  1. Aggregate only numeric columns: df.groupby('g')[numeric_cols].mean().
  2. Use an agg spec that selects per-column reductions, excluding the string column from arithmetic aggregations.
  3. If the column should be object dtype, cast it: df['col'] = df['col'].astype(object) (only if object semantics are truly wanted).

Example fix

// before
df.groupby('g').mean()  # TypeError on 'str' column

// after
num = df.select_dtypes(include='number').columns
df.groupby('g')[list(num)].mean()
Defensive patterns

Strategy: validation

Validate before calling

from pandas.core.arrays.string_ import StringDtype
string_ops = {'prod','mean','median','cumsum','cumprod','std','sem','var','skew','kurt'}
if isinstance(arr.dtype, StringDtype) and how in string_ops:
    raise TypeError(f"dtype '{arr.dtype}' does not support '{how}'")

Type guard

def is_string_dtype_obj(arr) -> bool:
    from pandas.core.arrays.string_ import StringDtype
    return isinstance(arr.dtype, StringDtype)

Try / catch

try:
    out = df.groupby('g').mean()
except TypeError:
    num = df.select_dtypes(include='number').columns
    out = df.groupby('g')[list(num)].mean()

Prevention

When it happens

Trigger: Calling groupby aggregations like df.groupby('g').mean(), .prod(), .std(), .median() on a DataFrame that contains a StringArray/'str' column (the new pyarrow-backed or object-backed string dtype). The groupby engine routes the string block into ExtensionArray._grouped_reduce which raises TypeError naming the unsupported operation.

Common situations: Migrating to pandas' string dtype (pd.StringDtype / 'str') where a whole-frame groupby aggregation now hits a string column that previously sat as object and silently produced NaN. Running df.groupby(...).agg(['mean','std',...]) across all columns including string ones.

Related errors


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

Appendix: source

Thrown at pandas/core/arrays/base.py:3076

        op = WrappedCythonOp(how=how, kind=kind, has_dropped_na=has_dropped_na)

        initial: Any = 0
        # GH#43682
        if isinstance(self.dtype, StringDtype):
            # StringArray
            if op.how in [
                "prod",
                "mean",
                "median",
                "cumsum",
                "cumprod",
                "std",
                "sem",
                "var",
                "skew",
                "kurt",
            ]:
                raise TypeError(
                    f"dtype '{self.dtype}' does not support operation '{how}'"
                )
            if op.how not in ["any", "all"]:
                # Fail early to avoid conversion to object
                op._get_cython_function(op.kind, op.how, np.dtype(object), False)

            arr = self
            if op.how == "sum":
                initial = ""
                # https://github.com/pandas-dev/pandas/issues/60229
                # All NA should result in the empty string.
                assert "skipna" in kwargs
                if kwargs["skipna"] and min_count == 0:
                    arr = arr.fillna("")
            npvalues = arr.to_numpy(object, na_value=np.nan)
        else:
            raise NotImplementedError(
                f"function is not implemented for this dtype: {self.dtype}"

View on GitHub (pinned to 3b7651241d)