pola-rs/polars · error · ValueError

dimensions of columns arg

Error message

dimensions of columns arg ({len(columns)}) must match data dimensions ({len(data)})

What it means

Raised by _handle_columns_arg when a `columns` list is passed but its length differs from the number of columns in the constructed data. After empty-data special-casing, Polars requires an exact 1:1 correspondence between replacement names and data columns.

Solutions

  1. Pass a columns list with exactly as many names as data columns
  2. Use schema={'name': dtype} instead if you also need dtypes
  3. Compute columns dynamically from the data, e.g. columns=[f'c{i}' for i in range(len(data))]

Example fix

// before
pl.DataFrame({'a': [1], 'b': [2]}, columns=['x', 'y', 'z'])
// after
pl.DataFrame({'a': [1], 'b': [2]}, columns=['x', 'y'])
Defensive patterns

Strategy: validation

Validate before calling

if columns is not None and data is not None and len(data) != len(columns):
    raise ValueError('columns names count must equal number of data columns')

Try / catch

try:
    df = pl.DataFrame(data, columns=columns)
except ValueError as e:
    if 'must match data dimensions' in str(e):
        df = pl.DataFrame(data)
    else:
        raise

Prevention

When it happens

Trigger: pl.DataFrame({'a':[1],'b':[2]}, columns=['x','y','z']); also numpy_to_pydf, series_to_pydf, dataframe_to_pydf, and sequence-based constructors called with a columns list of the wrong length.

Common situations: Hardcoded column-name list not updated after data shape changes, combining multiple data sources into one constructor call, off-by-one from including/excluding an index column name.

Related errors


AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18). Data as JSON: /api/errors/fabf0e368ee4ac68. Report an issue: GitHub.

Appendix: source

Thrown at py-polars/src/polars/_utils/construction/dataframe.py:272

        column_dtypes.update(schema_overrides)

    return column_names, column_dtypes


def _handle_columns_arg(
    data: list[PySeries],
    columns: Sequence[str] | None = None,
    *,
    from_dict: bool = False,
) -> list[PySeries]:
    """Rename data according to columns argument."""
    if columns is None:
        return data
    elif not data:
        return [pl.Series(name=c)._s for c in columns]
    elif len(data) != len(columns):
        msg = f"dimensions of columns arg ({len(columns)}) must match data dimensions ({len(data)})"
        raise ValueError(msg)

    if from_dict:
        series_map = {s.name(): s for s in data}
        if all((col in series_map) for col in columns):
            return [series_map[col] for col in columns]

    for i, c in enumerate(columns):
        if c != data[i].name():
            data[i] = data[i].clone()
            data[i].rename(c)

    return data


def _post_apply_columns(
    pydf: PyDataFrame,
    columns: SchemaDefinition | None,
    structs: dict[str, Struct] | None = None,

View on GitHub (pinned to fe841f959e)