pola-rs/polars · error

dimensions of `schema

Error message

dimensions of `schema` ({n_schema_cols}) must match data dimensions ({n_columns})

What it means

In `numpy_to_pydf`, when a `schema` is supplied its length must match the number of columns derived from the data. The only exception: a 1-D array with a 1-element schema is allowed. Otherwise ValueError is raised.

Solutions

  1. Make len(schema) equal the array's second dimension (number of columns).
  2. Pass schema as a dict of {name: dtype} built from the actual array width.
  3. If unsure, omit `schema` and let Polars infer names, then rename with .rename().

Example fix

// before
pl.from_numpy(arr, schema=['a', 'b'])  # arr has 3 columns
// after
pl.from_numpy(arr, schema=['a', 'b', 'c'])  # or schema={f'c{i}': pl.Float64 for i in range(arr.shape[1])}
Defensive patterns

Strategy: validation

Validate before calling

n_cols = arr.shape[1] if arr.ndim == 2 else 1
if schema is not None and len(schema) != n_cols and not (arr.ndim == 1 and len(schema) == 1):
    raise ValueError(f'schema has {len(schema)} names but data has {n_cols} columns')

Try / catch

try:
    df = pl.from_numpy(arr, schema=schema)
except ValueError as e:
    if 'must match data dimensions' in str(e):
        schema = [f'c{i}' for i in range(arr.shape[-1])]
        df = pl.from_numpy(arr, schema=schema)
    else:
        raise

Prevention

When it happens

Trigger: pl.from_numpy(arr, schema=[...]) where len(schema) != arr.shape[1] (for 2-D) or != 1 (for 1-D arrays).

Common situations: Hard-coded column name lists that drift from the data after changing array width; reusing a schema from a different dataset; forgetting a 2-D array with a single column still has n_columns = 1 but an array widened by a code change.

Related errors


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

Appendix: source

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

            elif orient == "row":
                n_columns = shape[1]
            elif orient == "col":
                n_columns = shape[0]
            else:
                msg = f"`orient` must be one of {{'col', 'row', None}}, got {orient!r}"
                raise ValueError(msg)
        else:
            if shape == ():
                msg = "cannot create DataFrame from zero-dimensional array"
            else:
                msg = f"cannot create DataFrame from array with more than two dimensions; shape = {shape}"
            raise ValueError(msg)

    if schema is not None and len(schema) != n_columns:
        if (n_schema_cols := len(schema)) != 1:
            msg = f"dimensions of `schema` ({n_schema_cols}) must match data dimensions ({n_columns})"
            raise ValueError(msg)
        n_columns = n_schema_cols

    column_names, schema_overrides = _unpack_schema(
        schema, schema_overrides=schema_overrides, n_expected=n_columns
    )

    # Convert data to series
    if structured_array:
        data_series = [
            pl.Series(
                name=series_name,
                values=data[record_name],
                dtype=schema_overrides.get(record_name),
                strict=strict,
                nan_to_null=nan_to_null,
            )._s
            for series_name, record_name in zip(column_names, record_names, strict=True)
        ]

View on GitHub (pinned to fe841f959e)