{"record":{"id":"762933c89124b702","repo":"pola-rs/polars","slug":"not-allowed-to-set-dataframe-by-boolean-mask-in-th","errorCode":null,"errorMessage":"not allowed to set DataFrame by boolean mask in the row position\n\nConsider using `DataFrame.with_columns`.","messagePattern":"not allowed to set DataFrame by boolean mask in the row position\n\nConsider using `DataFrame\\.with_columns`\\.","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/dataframe/frame.py","lineNumber":1578,"sourceCode":"\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                )\n                raise TypeError(msg)\n\n            # get series column selection\n            if isinstance(col_selection, str):\n                s = self.__getitem__(col_selection)\n            elif isinstance(col_selection, int):\n                s = self[:, col_selection]\n            else:\n                msg = f\"unexpected column selection {col_selection!r}\"\n                raise TypeError(msg)\n\n            # dispatch to __setitem__ of Series to do modification\n            s[row_selection] = value\n\n            # now find the location to place series\n            # df[idx]\n            if isinstance(col_selection, int):\n                self.replace_column(col_selection, s)\n            # df[\"foo\"]","sourceCodeStart":1560,"sourceCodeEnd":1596,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/dataframe/frame.py#L1560-L1596","documentation":"DataFrame.__setitem__ with a (row, col) tuple key rejects boolean row selectors: a pl.Series with Boolean dtype or a list of bools. Mask-based cell assignment would require hidden, order-dependent copying and is intentionally unsupported; the error redirects to with_columns for conditional updates.","triggerScenarios":"df[mask_series, 'col'] = value where mask_series.dtype == pl.Boolean; df[[True, False, ...], 5] = 0; df[df['a'] > 1, 'a'] = -1.","commonSituations":"Ported pandas conditional assignment (df.loc[df.a > 1, 'a'] = v pattern); sentinel/replacement loops that try to zero out flagged rows; validation code marking bad cells by mask.","solutions":["Use conditional expression: df = df.with_columns(pl.when(pl.col('a') > 1).then(-1).otherwise(pl.col('a')).alias('a'))","With an external boolean Series mask: df = df.with_columns(pl.when(pl.Series(mask)).then(value).otherwise(pl.col('a')).alias('a'))","To set by integer positions, use row-selection with integers/ranges instead of masks"],"exampleFix":"# before\ndf[df['qty'] < 0, 'qty'] = 0\n\n# after\ndf = df.with_columns(\n    pl.when(pl.col('qty') < 0).then(0).otherwise(pl.col('qty')).alias('qty')\n)","handlingStrategy":"validation","validationCode":"# masks are rejected by design; express the conditional update declaratively instead\ndf = df.with_columns(\n    pl.when(pl.col('qty') < 0).then(0).otherwise(pl.col('qty')).alias('qty')\n)","typeGuard":"import polars as pl\n\ndef is_boolean_row_selection(sel: object) -> bool:\n    return (isinstance(sel, pl.Series) and sel.dtype == pl.Boolean) or (\n        isinstance(sel, list) and all(isinstance(v, bool) for v in sel)\n    )\n# if is_boolean_row_selection(row_sel): use pl.when(...) instead of __setitem__","tryCatchPattern":null,"preventionTips":["Translate pandas df.loc[mask, col] = v to with_columns + pl.when/then/otherwise","Never build (row, col) tuple __setitem__ calls with boolean masks","Wrap external boolean Series as pl.when(pl.Series(mask)) when applying them to columns"],"tags":["setitem","boolean-mask","with-columns","pandas-migration"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}