{"record":{"id":"b5230d09cdd098e7","repo":"pandas-dev/pandas","slug":"cannot-broadcast-result","errorCode":null,"errorMessage":"cannot broadcast result","messagePattern":"cannot broadcast result","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/apply.py","lineNumber":1269,"sourceCode":"    def apply_broadcast(self, target: DataFrame) -> DataFrame:\n        assert callable(self.func)\n\n        result_values = np.empty_like(target.values)\n\n        # axis which we want to compare compliance\n        result_compare = target.shape[0]\n\n        for i, col in enumerate(target.columns):\n            res = self.func(target[col], *self.args, **self.kwargs)\n            ares = np.asarray(res).ndim\n\n            # must be a scalar or 1d\n            if ares > 1:\n                raise ValueError(\"too many dims to broadcast\")\n            if ares == 1:\n                # must match return dim\n                if result_compare != len(res):\n                    raise ValueError(\"cannot broadcast result\")\n\n            result_values[:, i] = res\n\n        # we *always* preserve the original index / columns\n        result = self.obj._constructor(\n            result_values, index=target.index, columns=target.columns\n        )\n        return result\n\n    def apply_standard(self):\n        if self.engine == \"python\":\n            results, res_index = self.apply_series_generator()\n        else:\n            results, res_index = self.apply_series_numba()\n\n        # wrap results\n        return self.wrap_results(results, res_index)\n","sourceCodeStart":1251,"sourceCodeEnd":1287,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/apply.py#L1251-L1287","documentation":"Raised inside `apply_broadcast` when a per-column UDF result is 1-D but its length does not equal `target.shape[0]` (the frame's row count). Broadcast mode places the result back into a column of fixed length, so a length mismatch is rejected rather than silently truncated or padded.","triggerScenarios":"`df.apply(func, result_type='broadcast')` where `func(df[col])` returns a 1-D array/Series whose `len(...)` differs from the number of rows. E.g. `df.apply(lambda s: s.dropna().values, result_type='broadcast')` (drops NaNs, shorter than input), or `lambda s: s.head(5)`.","commonSituations":"UDFs that filter (`dropna`, `drop_duplicates`, `head`), resample, or otherwise change length inside a broadcast apply; assuming broadcast will pad/align like a transform.","solutions":["Ensure the UDF returns exactly `len(df)` values per column (do not filter inside the UDF).","If filtering is needed, perform it before the apply or reindex the result to the original index inside the UDF.","Use `df.transform(func)` instead of `df.apply(func, result_type='broadcast')` if you want index-aligned same-length outputs — transform enforces the contract with a clearer message."],"exampleFix":"// before\ndf.apply(lambda s: s.dropna(), result_type='broadcast')\n// after\ndf.apply(lambda s: s.dropna().reindex(df.index), result_type='broadcast')","handlingStrategy":"validation","validationCode":"def broadcast_apply_length_safe(df, func):\n    n = len(df)\n    for col in df.columns:\n        res = func(df[col].head(2))\n        import numpy as np\n        arr = np.asarray(res)\n        if arr.ndim == 1 and len(arr) != n:\n            raise ValueError(f'{func.__name__} returns length {len(arr)} for column {col!r}; expected {n}')\n    return df.apply(func, result_type='broadcast')","typeGuard":"def func_preserves_length(func, series) -> bool:\n    import numpy as np\n    try:\n        arr = np.asarray(func(series))\n        return arr.ndim <= 1 and len(arr) == len(series)\n    except Exception:\n        return False","tryCatchPattern":"try:\n    out = df.apply(func, result_type='broadcast')\nexcept ValueError as e:\n    if 'cannot broadcast result' in str(e):\n        out = df.transform(func)  # transform enforces same-length contract more clearly\n    else:\n        raise","preventionTips":["Never filter rows (dropna/head) inside a broadcast UDF.","Reindex UDF results back to df.index before returning.","Prefer df.transform for same-length elementwise ops."],"tags":["pandas","apply","broadcast","length-mismatch","valueerror"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}