{"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/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/apply.py#L1251-L1287","documentation":"Raised in DataFrame.apply_broadcast (apply.py:1269) when func, run with result_type='broadcast', returns a 1-D array whose length does not equal the number of rows in the target frame (result_compare != len(res)). Broadcasting requires the per-column return to align exactly with target.shape[0] so it can be assigned into result_values[:, i]; a length mismatch means the broadcast cannot be assembled.","triggerScenarios":"df.apply(func, result_type='broadcast') where func returns a 1-D array/Series whose len differs from len(df). For example, func does a groupby/agg that changes length, or returns c.dropna() which shortens the column. Hit at apply.py:1268-1269.","commonSituations":"Func calls .value_counts(), .unique(), .dropna(), or .sample() on the column, changing its length; returning a derived array indexed differently than the frame; broadcasting expectations mismatched with a downsample/aggregation step.","solutions":["Ensure func returns an array with exactly len(df) elements per column - reindex or pad as needed.","Move length-changing logic (groupby, resample, dropna) out of the broadcast func and into a separate transform step.","If the result truly has a different length, drop result_type='broadcast' and use plain apply or agg with the right shape semantics."],"exampleFix":"// before\ndf.apply(lambda c: c.dropna(), result_type='broadcast')\n// after\ndf.apply(lambda c: c.fillna(0), result_type='broadcast')","handlingStrategy":"validation","validationCode":"import numpy as np\nsample = np.asarray(func(df[df.columns[0]], *args, **kwargs))\nif sample.ndim == 1 and len(sample) != len(df):\n    raise ValueError(f'func returned length {len(sample)} but frame has {len(df)} rows; cannot broadcast')","typeGuard":"def broadcast_length_matches(func, target_len: int, sample_input) -> bool:\n    import numpy as np\n    r = np.asarray(func(sample_input))\n    return r.ndim == 0 or (r.ndim == 1 and len(r) == target_len)","tryCatchPattern":"try:\n    df.apply(func, result_type='broadcast')\nexcept ValueError as e:\n    if 'cannot broadcast result' in str(e):\n        df.apply(lambda c: func(c).reindex(df.index), result_type='broadcast')\n    else:\n        raise","preventionTips":["Keep func idempotent in length - never call dropna/value_counts/unique inside a broadcast func.","If you need a length-changing transform, do it before apply and reindex to df.index."],"tags":["pandas","apply","broadcast","shape","length-mismatch"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}