pandas-dev/pandas · error · ValueError

cannot combine transform and aggregation operations

Error message

cannot combine transform and aggregation operations

What it means

Raised inside `wrap_results_list_like` after a list-like aggregation/transform produces a nested result that cannot be concatenated into a flat Series. When the per-column results are themselves list-like (nested objects) pandas refuses to silently flatten, because that would mask a user mistake of mixing transform-style (same-shape) and aggregation-style (reduced) operations in one call.

Solutions

  1. Split the call: perform aggregators with `df.agg([...])` and transforms with `df.transform([...])` separately, then concatenate.
  2. Make every function in the list return the same shape kind (all scalars, or all same-length Series).
  3. If a UDF is the culprit, make its return shape deterministic across columns.

Example fix

// before
df.agg(['mean', lambda s: s + 1])
// after
agg_part = df.agg(['mean'])
trans_part = df.transform([lambda s: s + 1])
Defensive patterns

Strategy: validation

Validate before calling

def safe_list_agg(df, funcs):
    import pandas as pd
    # Verify each func produces the same result shape kind (all scalar or all same-length).
    probes = [df.head(2).apply(f) for f in funcs]
    kinds = {type(p).__name__ for p in probes}
    if len(kinds) > 1:
        raise ValueError('Mixed transform/aggregation in list-like agg; split the call')
    return df.agg(funcs)

Type guard

def funcs_have_uniform_shape(funcs, obj) -> bool:
    import pandas as pd
    probe = obj.head(2) if hasattr(obj, 'head') else obj
    shapes = []
    for f in funcs:
        r = probe.apply(f)
        shapes.append('ndframe' if hasattr(r, 'ndim') and r.ndim >= 1 else 'scalar')
    return len(set(shapes)) == 1

Try / catch

try:
    out = df.agg(funcs)
except ValueError as e:
    if 'cannot combine transform and aggregation' in str(e):
        out = pd.concat([df.agg([f]) for f in funcs], axis=1)
    else:
        raise

Prevention

When it happens

Trigger: Calling `df.agg([func1, func2])` (or transform) where some funcs return scalars and others return Series/array-likes, producing a nested object. Or passing a list of functions where at least one is a reducer and another is elementwise. Triggered in the TypeError-fallback path of `concat(results, ...)`.

Common situations: Mixing aggregation and transformation in a single list-like `.agg([...])` call, e.g. `df.agg(['mean', lambda s: s])`. Or a UDF whose return shape varies by column dtype.

Related errors


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

Appendix: source

Thrown at pandas/core/apply.py:540

            keys = selected_obj.columns.take(indices)  # type: ignore[assignment]

        return keys, results

    def wrap_results_list_like(
        self, keys: Iterable[Hashable], results: list[Series | DataFrame]
    ):
        obj = self.obj

        try:
            return concat(results, keys=keys, axis=1, sort=False)
        except TypeError as err:
            # we are concatting non-NDFrame objects,
            # e.g. a list of scalars
            from pandas import Series

            result = Series(results, index=keys, name=obj.name)
            if is_nested_object(result):
                raise ValueError(
                    "cannot combine transform and aggregation operations"
                ) from err
            return result

    def agg_dict_like(self) -> DataFrame | Series:
        """
        Compute aggregation in the case of a dict-like argument.

        Returns
        -------
        Result of aggregation.
        """
        return self.agg_or_apply_dict_like(op_name="agg")

    def compute_dict_like(
        self,
        op_name: Literal["agg", "apply"],
        selected_obj: Series | DataFrame,

View on GitHub (pinned to 3b7651241d)