{"record":{"id":"685bf6be26eebd1d","repo":"pola-rs/polars","slug":"dataframe-object-does-not-support-series-assignm","errorCode":null,"errorMessage":"DataFrame object does not support `Series` assignment by index\n\nUse `DataFrame.with_columns`.","messagePattern":"DataFrame object does not support `Series` assignment by index\n\nUse `DataFrame\\.with_columns`\\.","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/dataframe/frame.py","lineNumber":1548,"sourceCode":"        >>> df\n        shape: (3, 2)\n        ┌─────┬─────┐\n        │ a   ┆ b   │\n        │ --- ┆ --- │\n        │ i64 ┆ i64 │\n        ╞═════╪═════╡\n        │ 10  ┆ 30  │\n        │ 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","sourceCodeStart":1530,"sourceCodeEnd":1566,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/dataframe/frame.py#L1530-L1566","documentation":"DataFrame.__setitem__ explicitly rejects df['col'] = value (string key). Polars DataFrames are not dict-like mutable containers of Series; in-place column mutation by name is disallowed by design, and the error message redirects to the functional alternative with_columns that returns a new frame.","triggerScenarios":"df['new_col'] = [1, 2, 3]; df['existing'] = df['existing'] * 2; df[f'{name}_x'] = series — any assignment whose key is a single string.","commonSituations":"Direct port of pandas mutation code; notebook-style incremental column addition loops; helper functions that take a df and 'annotate' it in place; duck-typed code shared between pandas and polars.","solutions":["Use with_columns: df = df.with_columns(pl.Series('new_col', [1, 2, 3])) or df = df.with_columns((pl.col('existing') * 2).alias('existing'))","For multiple columns: df = df.with_columns(new_a=pl.Series([...]), new_b=...)","Refactor functions to return the new frame instead of mutating: df = annotate(df)"],"exampleFix":"# before\ndf['ratio'] = df['a'] / df['b']\n\n# after\ndf = df.with_columns((pl.col('a') / pl.col('b')).alias('ratio'))","handlingStrategy":"validation","validationCode":"# there is no runtime guard that makes df['col'] = v legal;\n# route all column writes through a helper:\ndef add_col(df, name, values):\n    return df.with_columns(pl.Series(name, values))\n\ndf = add_col(df, 'ratio', df['a'] / df['b'])","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Ban __setitem__ on DataFrames in shared code; always with_columns","Search for `\\[[\"']\\w+[\"']\\]\\s*=` patterns when porting pandas code","Design helpers to return new frames instead of mutating a passed-in df"],"tags":["setitem","mutation","with-columns","pandas-migration"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}