{"record":{"id":"12d9b33960fa1f8b","repo":"pandas-dev/pandas","slug":"too-many-dims-to-broadcast","errorCode":null,"errorMessage":"too many dims to broadcast","messagePattern":"too many dims to broadcast","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/apply.py","lineNumber":1265,"sourceCode":"            return self.obj._constructor(result, index=self.index, columns=self.columns)\n        else:\n            return self.obj._constructor_sliced(result, index=self.agg_axis)\n\n    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()","sourceCodeStart":1247,"sourceCodeEnd":1283,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/apply.py#L1247-L1283","documentation":"Raised inside DataFrame.apply_broadcast (apply.py:1265) when the user-supplied func, applied to a column under result_type='broadcast', returns an array with more than one dimension. Broadcasting requires each per-column return to be a scalar or a 1-D array sized to the frame's row count; a 2-D (or higher) return cannot be assigned back into the single column slice result_values[:, i].","triggerScenarios":"df.apply(func, result_type='broadcast') where func returns a 2-D numpy array, DataFrame, or any ndarray with ndim >= 2. Hit in apply_broadcast at apply.py:1261-1265 when np.asarray(res).ndim > 1.","commonSituations":"Func intended to return a single column but actually returns a reshaped 2-D array (e.g. np.reshape(x, (-1,1))); func computing a DataFrame of multiple columns when broadcast expects one; transposing mistakes that flip the result shape.","solutions":["Make func return a scalar or a 1-D array/Series per column. If it currently returns a 2-D array, flatten with .ravel() or .squeeze().","If you genuinely need multiple output columns, switch away from result_type='broadcast' to the default apply (which infers columns from a dict/Series return) or use result_type='expand'.","Inspect the return shape with a quick standalone call to func(df[df.columns[0]]) and adjust before running the full apply."],"exampleFix":"// before\ndf.apply(lambda c: np.reshape(c.values*2, (-1,1)), result_type='broadcast')\n// after\ndf.apply(lambda c: (c.values*2).ravel(), result_type='broadcast')","handlingStrategy":"validation","validationCode":"import numpy as np\nsample = func(df[df.columns[0]], *args, **kwargs)\nif np.asarray(sample).ndim > 1:\n    raise ValueError('func must return a scalar or 1-D array when result_type=broadcast')","typeGuard":"def returns_at_most_1d(func, sample_input) -> bool:\n    import numpy as np\n    return np.asarray(func(sample_input)).ndim <= 1","tryCatchPattern":"try:\n    df.apply(func, result_type='broadcast')\nexcept ValueError as e:\n    if 'too many dims' in str(e):\n        df.apply(lambda c: np.asarray(func(c)).ravel(), result_type='broadcast')\n    else:\n        raise","preventionTips":["Unit-test func on a single column and assert ndim <= 1 before broadcasting.","Avoid reshape(-1,1) inside broadcast funcs; that forces a 2-D return."],"tags":["pandas","apply","broadcast","shape","numpy"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}