pola-rs/polars · error · ValueError
can only set multiple columns with 2D matrix
Error message
can only set multiple columns with 2D matrix
What it means
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.
Source
Thrown at py-polars/src/polars/dataframe/frame.py:1556
│ 100 ┆ 50 │
│ 30 ┆ 60 │
└─────┴─────┘
"""
# df["foo"] = series
if isinstance(key, str):
msg = (
"DataFrame object does not support `Series` assignment by index"
"\n\nUse `DataFrame.with_columns`."
)
raise TypeError(msg)
# df[["C", "D"]]
elif isinstance(key, list):
# TODO: Use python sequence constructors
value = np.array(value)
if value.ndim != 2:
msg = "can only set multiple columns with 2D matrix"
raise ValueError(msg)
if value.shape[1] != len(key):
msg = "matrix columns should be equal to list used to determine column names"
raise ValueError(msg)
# TODO: we can parallelize this by calling from_numpy
columns = []
for i, name in enumerate(key):
columns.append(pl.Series(name, value[:, i]))
self._df = self.with_columns(columns)._df
# df[a, b]
elif isinstance(key, tuple):
row_selection, col_selection = key
if (
isinstance(row_selection, pl.Series) and row_selection.dtype == Boolean
) or is_bool_sequence(row_selection):
msg = (View on GitHub (pinned to df599052da)
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']])
Example fix
# before
df[['C', 'D']] = [1, 2, 3]
# after
import numpy as np
df[['C', 'D']] = np.column_stack([1, 2, 3, 4]) # shape (2, 2)
# or
df = df.with_columns(pl.Series('C', [1, 2]), pl.Series('D', [3, 4])) Defensive patterns
Strategy: validation
Validate before calling
import numpy as np
value = np.asarray(value)
if value.ndim != 2:
raise ValueError(f'need 2-D matrix for multi-column set; got ndim={value.ndim}')
df[keys] = value Prevention
- 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__
When it happens
Trigger: 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.
Common situations: Pandas-style broadcast assignment ported to polars; feeding a flat column buffer where column-major pairs were intended.
Related errors
- matrix columns should be equal to list used to determine col
- DataFrame object does not support `Series` assignment by ind
- not allowed to set DataFrame by boolean mask in the row posi
- cannot use `__setitem__` on DataFrame with key {key!r} of ty
- data does not match the number of columns
AI-assisted analysis of pola-rs/polars@df599052da (2026-08-16).
Data as JSON: /api/errors/d736904fba082494.
Report an issue: GitHub.