{"record":{"id":"efdcf192cd8e04ee","repo":"pandas-dev/pandas","slug":"transform-function-failed","errorCode":null,"errorMessage":"Transform function failed","messagePattern":"Transform function failed","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/apply.py","lineNumber":393,"sourceCode":"                )\n            # Convert func equivalent dict\n            if is_series:\n                func = {com.get_callable_name(v) or v: v for v in func}\n            else:\n                func = dict.fromkeys(obj, func)\n\n        if is_dict_like(func):\n            func = cast(\"AggFuncTypeDict\", func)\n            return self.transform_dict_like(func)\n\n        # func is either str or callable\n        func = cast(\"AggFuncTypeBase\", func)\n        try:\n            result = self.transform_str_or_callable(func)\n        except TypeError:\n            raise\n        except Exception as err:\n            raise ValueError(\"Transform function failed\") from err\n\n        # Functions that transform may return empty Series/DataFrame\n        # when the dtype is not appropriate\n        if (\n            isinstance(result, (ABCSeries, ABCDataFrame))\n            and result.empty\n            and not obj.empty\n        ):\n            raise ValueError(\"Transform function failed\")\n        if not isinstance(result, (ABCSeries, ABCDataFrame)) or not result.index.equals(\n            obj.index\n        ):\n            raise ValueError(\"Function did not transform\")\n\n        return result\n\n    def transform_dict_like(self, func) -> DataFrame:\n        \"\"\"","sourceCodeStart":375,"sourceCodeEnd":411,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/apply.py#L375-L411","documentation":"Raised inside `Apply.transform` when the user-supplied transform function raises a non-TypeError exception while executing on a str-or-callable path. The original exception is chained via `from err`. This indicates the function ran but failed (e.g. arithmetic error, missing attribute) rather than being structurally invalid.","triggerScenarios":"Calling `df.transform(func)` where `func` raises an exception internally (e.g. division by zero, KeyError on a column, numpy ValueError on bad dtype) but not a TypeError. The wrapper catches Exception, rewraps as ValueError('Transform function failed').","commonSituations":"Passing a function that assumes a dtype the column doesn't have (e.g. `np.log` on object column); functions that reference missing columns; chained operations where an intermediate step fails; debugging confusion because the original traceback is chained but the top message is generic.","solutions":["Inspect the chained exception (`__cause__`) — the original traceback shows the real failure; fix that root cause.","Test the function on a single column/Series first via `func(df['col'])` to reproduce the underlying error directly.","Add dtype/column pre-checks in your transform function and raise a more informative error."],"exampleFix":"# before\ndf.transform(lambda s: np.log(s))  # fails on object dtypes\n# after\nnum = df.select_dtypes(include='number')\nnum.transform(lambda s: np.log(s))","handlingStrategy":"try-catch","validationCode":"def test_func_on_series(func, s):\n    \"\"\"Smoke-test a transform func on one column before applying frame-wide.\"\"\"\n    try:\n        out = func(s.copy())\n        return out is not None\n    except Exception:\n        return False\n\nif test_func_on_series(my_func, df[df.columns[0]]):\n    df.transform(my_func)","typeGuard":null,"tryCatchPattern":"try:\n    df.transform(my_func)\nexcept ValueError as e:\n    if 'Transform function failed' in str(e) and e.__cause__ is not None:\n        raise RuntimeError(f'underlying error: {e.__cause__!r}') from e.__cause__\n    raise","preventionTips":["Always inspect the chained __cause__ when you see 'Transform function failed'.","Unit-test transform functions on a single column before applying frame-wide."],"tags":["pandas","transform","valueerror","user-function","chained-exception"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}