{"record":{"id":"736f3f65be66125e","repo":"pola-rs/polars","slug":"matrix-columns-should-be-equal-to-list-used-to-det","errorCode":null,"errorMessage":"matrix columns should be equal to list used to determine column names","messagePattern":"matrix columns should be equal to list used to determine column names","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/dataframe/frame.py","lineNumber":1559,"sourceCode":"        \"\"\"\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 = (\n                    \"not allowed to set DataFrame by boolean mask in the row position\"\n                    \"\\n\\nConsider using `DataFrame.with_columns`.\"\n                )","sourceCodeStart":1541,"sourceCodeEnd":1577,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/dataframe/frame.py#L1541-L1577","documentation":"In multi-column __setitem__ (df[['C', 'D']] = matrix), after the 2-D check passes, the matrix's second dimension must equal the number of column names supplied. A mismatch means columns would be silently dropped or missing, so the assignment aborts with ValueError before mutating anything.","triggerScenarios":"df[['C', 'D']] = arr where arr.shape == (n, 3) or (n, 1); assigning a 3-wide matrix to ['C', 'D', 'E'] list of two names; off-by-one column lists after editing code.","commonSituations":"Generated code where the key list and matrix width come from different sources; refactors that add a column to the matrix but not the names; transposed matrices (shape (k, n) instead of (n, k)).","solutions":["Align the names to the matrix: assert arr.shape[1] == len(names), or slice arr = arr[:, :len(names)]","If the matrix is transposed, fix orientation: arr = arr.T so axis 1 is columns","Prefer explicit construction: df = df.with_columns([pl.Series(name, arr[:, i]) for i, name in enumerate(names)])"],"exampleFix":"# before\nnames = ['C', 'D']\ndf[names] = np.ones((df.height, 3))  # 3 cols vs 2 names\n\n# after\nnames = ['C', 'D']\nmatrix = np.ones((df.height, len(names)))\ndf[names] = matrix","handlingStrategy":"validation","validationCode":"import numpy as np\n\nvalue = np.asarray(value)\nassert value.ndim == 2 and value.shape[1] == len(keys), (value.shape, keys)\ndf[keys] = value","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Derive the key list and matrix from one source of truth (e.g. array columns from the same list)","Assert shape[1] == len(keys) before assignment in generated/dynamic code","Check for transposition (rows/cols swapped) when matrices come from external tools"],"tags":["setitem","numpy","shape-mismatch","columns"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}