{"record":{"id":"95ecfc95abe9b387","repo":"pandas-dev/pandas","slug":"cannot-combine-transform-and-aggregation-operation","errorCode":null,"errorMessage":"cannot combine transform and aggregation operations","messagePattern":"cannot combine transform and aggregation operations","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/apply.py","lineNumber":540,"sourceCode":"            keys = selected_obj.columns.take(indices)  # type: ignore[assignment]\n\n        return keys, results\n\n    def wrap_results_list_like(\n        self, keys: Iterable[Hashable], results: list[Series | DataFrame]\n    ):\n        obj = self.obj\n\n        try:\n            return concat(results, keys=keys, axis=1, sort=False)\n        except TypeError as err:\n            # we are concatting non-NDFrame objects,\n            # e.g. a list of scalars\n            from pandas import Series\n\n            result = Series(results, index=keys, name=obj.name)\n            if is_nested_object(result):\n                raise ValueError(\n                    \"cannot combine transform and aggregation operations\"\n                ) from err\n            return result\n\n    def agg_dict_like(self) -> DataFrame | Series:\n        \"\"\"\n        Compute aggregation in the case of a dict-like argument.\n\n        Returns\n        -------\n        Result of aggregation.\n        \"\"\"\n        return self.agg_or_apply_dict_like(op_name=\"agg\")\n\n    def compute_dict_like(\n        self,\n        op_name: Literal[\"agg\", \"apply\"],\n        selected_obj: Series | DataFrame,","sourceCodeStart":522,"sourceCodeEnd":558,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/apply.py#L522-L558","documentation":"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.","triggerScenarios":"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, ...)`.","commonSituations":"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.","solutions":["Split the call: perform aggregators with `df.agg([...])` and transforms with `df.transform([...])` separately, then concatenate.","Make every function in the list return the same shape kind (all scalars, or all same-length Series).","If a UDF is the culprit, make its return shape deterministic across columns."],"exampleFix":"// before\ndf.agg(['mean', lambda s: s + 1])\n// after\nagg_part = df.agg(['mean'])\ntrans_part = df.transform([lambda s: s + 1])","handlingStrategy":"validation","validationCode":"def safe_list_agg(df, funcs):\n    import pandas as pd\n    # Verify each func produces the same result shape kind (all scalar or all same-length).\n    probes = [df.head(2).apply(f) for f in funcs]\n    kinds = {type(p).__name__ for p in probes}\n    if len(kinds) > 1:\n        raise ValueError('Mixed transform/aggregation in list-like agg; split the call')\n    return df.agg(funcs)","typeGuard":"def funcs_have_uniform_shape(funcs, obj) -> bool:\n    import pandas as pd\n    probe = obj.head(2) if hasattr(obj, 'head') else obj\n    shapes = []\n    for f in funcs:\n        r = probe.apply(f)\n        shapes.append('ndframe' if hasattr(r, 'ndim') and r.ndim >= 1 else 'scalar')\n    return len(set(shapes)) == 1","tryCatchPattern":"try:\n    out = df.agg(funcs)\nexcept ValueError as e:\n    if 'cannot combine transform and aggregation' in str(e):\n        out = pd.concat([df.agg([f]) for f in funcs], axis=1)\n    else:\n        raise","preventionTips":["Never mix aggregators and elementwise funcs in one list-like agg call.","If unsure, run a 2-row probe of each func to confirm uniform result shape.","Split transform-style and aggregation-style work into separate calls."],"tags":["pandas","agg","transform","nested-result","valueerror"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}