pandas-dev/pandas · error · TypeError

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

Error message

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

What it means

Inside ExtensionArray._groupby_op (base.py:3076), a StringDtype array explicitly rejects a fixed list of non-sensical aggregations (prod, mean, median, cumsum, cumprod, std, sem, var, skew, kurt) with TypeError. Strings have no numeric meaning for these ops, so pandas fails fast rather than coercing to object.

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 71959b8cb9)

Solutions

  1. Pass numeric_only=True to the groupby aggregation so string columns are skipped.
  2. Select numeric columns before grouping: df.groupby(key)[numeric_cols].mean().
  3. Convert genuinely numeric string data with astype('Float64') before the aggregation.
  4. Drop the string column from the groupby target.

Example fix

# before
df.groupby("id").mean()  # raises if other cols are 'string'

# after
df.groupby("id").mean(numeric_only=True)
Defensive patterns

Strategy: validation

Validate before calling

def safe_groupby_agg(df, key, op):
    import pandas as pd
    if df.select_dtypes(exclude="number").shape[1]:
        return getattr(df.groupby(key), op)(numeric_only=True)
    return getattr(df.groupby(key), op)()

Type guard

def is_string_dtype_col(dtype) -> bool:
    import pandas as pd
    return dtype == "string" or pd.api.types.is_string_dtype(dtype)

Try / catch

try:
    df.groupby("id").mean()
except TypeError as e:
    if "does not support operation" in str(e):
        df.groupby("id").mean(numeric_only=True)
    else:
        raise

Prevention

When it happens

Trigger: Calling df.groupby(key).prod()/.mean()/.median()/.cumsum()/.std()/.var()/.sem()/.skew()/.kurt() (or Series groupby equivalents) on a 'string'-dtype column, or on a DataFrame whose only columns are string dtype.

Common situations: Applying df.groupby(...).mean() across a DataFrame that still has unconverted string columns; aggregating identifiers stored as strings; pipelines that assume all columns are numeric.

Related errors


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