{"record":{"id":"d736904fba082494","repo":"pola-rs/polars","slug":"can-only-set-multiple-columns-with-2d-matrix","errorCode":null,"errorMessage":"can only set multiple columns with 2D matrix","messagePattern":"can only set multiple columns with 2D matrix","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/dataframe/frame.py","lineNumber":1556,"sourceCode":"        │ 100 ┆ 50  │\n        │ 30  ┆ 60  │\n        └─────┴─────┘\n        \"\"\"\n        # df[\"foo\"] = series\n        if isinstance(key, str):\n            msg = (\n                \"DataFrame object does not support `Series` assignment by index\"\n                \"\\n\\nUse `DataFrame.with_columns`.\"\n            )\n            raise TypeError(msg)\n\n        # df[[\"C\", \"D\"]]\n        elif isinstance(key, list):\n            # TODO: Use python sequence constructors\n            value = np.array(value)\n            if value.ndim != 2:\n                msg = \"can only set multiple columns with 2D matrix\"\n                raise ValueError(msg)\n            if value.shape[1] != len(key):\n                msg = \"matrix columns should be equal to list used to determine column names\"\n                raise ValueError(msg)\n\n            # TODO: we can parallelize this by calling from_numpy\n            columns = []\n            for i, name in enumerate(key):\n                columns.append(pl.Series(name, value[:, i]))\n            self._df = self.with_columns(columns)._df\n\n        # df[a, b]\n        elif isinstance(key, tuple):\n            row_selection, col_selection = key\n\n            if (\n                isinstance(row_selection, pl.Series) and row_selection.dtype == Boolean\n            ) or is_bool_sequence(row_selection):\n                msg = (","sourceCodeStart":1538,"sourceCodeEnd":1574,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/dataframe/frame.py#L1538-L1574","documentation":"When assigning multiple columns at once via df[['C', 'D']] = value, polars converts value with np.array(value) and requires a 2-D matrix (one column per name, one row per frame row). A scalar, 1-D list, or higher-dimensional array fails the value.ndim != 2 check and raises ValueError.","triggerScenarios":"df[['C', 'D']] = [1, 2, 3] (1-D); df[['C', 'D']] = 5 (scalar broadcasts in pandas but not here); passing a 3-D array or a list-of-lists-of-lists.","commonSituations":"Pandas-style broadcast assignment ported to polars; feeding a flat column buffer where column-major pairs were intended.","solutions":["Supply a 2-D array with shape (df.height, len(key)): df[['C', 'D']] = np.column_stack([xs, ys])","Or use the idiomatic API: df = df.with_columns(pl.Series('C', xs), pl.Series('D', ys))","For broadcasting a scalar to many columns, build expressions: df = df.with_columns([pl.lit(v).alias(c) for c in ['C', 'D']])"],"exampleFix":"# before\ndf[['C', 'D']] = [1, 2, 3]\n\n# after\nimport numpy as np\ndf[['C', 'D']] = np.column_stack([1, 2, 3, 4])  # shape (2, 2)\n# or\ndf = df.with_columns(pl.Series('C', [1, 2]), pl.Series('D', [3, 4]))","handlingStrategy":"validation","validationCode":"import numpy as np\n\nvalue = np.asarray(value)\nif value.ndim != 2:\n    raise ValueError(f'need 2-D matrix for multi-column set; got ndim={value.ndim}')\ndf[keys] = value","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Always shape multi-column assignment inputs with np.column_stack or reshape(-1, len(keys))","Prefer with_columns(pl.Series(...), ...) over __setitem__ for clarity","Remember polars does not broadcast scalars in multi-column __setitem__"],"tags":["setitem","numpy","shape-mismatch","pandas-migration"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}