pola-rs/polars · error

cannot initialize Series from DataFrame without any columns

Error message

cannot initialize Series from DataFrame without any columns

What it means

`dataframe_to_pyseries` converts a Polars DataFrame to a single Series only when it has exactly one column (width == 1). If the DataFrame has zero or multiple columns, conversion is impossible and TypeError is raised (message says 'without any columns' but it triggers for width != 1 cases handled here).

Solutions

  1. Select exactly one column before converting: pl.Series(df['col']) or df.to_series().
  2. Check df.width before converting and handle width 0 / width > 1 explicitly.
  3. If multiple columns are needed, keep it as a DataFrame rather than a Series.

Example fix

// before
s = pl.Series(df.select())  # empty DataFrame
// after
if df.width == 1:
    s = pl.Series(df)
else:
    raise ValueError(f'expected 1 column, got {df.width}')
Defensive patterns

Strategy: validation

Validate before calling

if not isinstance(values, pl.Series) and values.width != 1:
    raise ValueError(f'need exactly 1 column to build a Series, got {values.width}')

Try / catch

try:
    s = pl.Series(df)
except TypeError as e:
    if 'without any columns' in str(e):
        s = df.to_series()  # or select a specific column
    else:
        raise

Prevention

When it happens

Trigger: pl.Series(df) or pl.Series(name, df) where df.width != 1 — notably an empty DataFrame with no columns, or a multi-column DataFrame.

Common situations: Selecting no columns from a DataFrame (df.select() yields width 0) then wrapping in Series; accidentally passing a whole multi-column DataFrame where a single column was intended.

Related errors


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

Appendix: source

Thrown at py-polars/src/polars/_utils/construction/series.py:578

def dataframe_to_pyseries(
    name: str | None,
    values: DataFrame,
    *,
    dtype: PolarsDataType | None = None,
    strict: bool = True,
) -> PySeries:
    """Construct a new PySeries from a Polars DataFrame."""
    if values.width > 1:
        name = name or ""
        s = values.to_struct(name)
    elif values.width == 1:
        s = values.to_series()
        if name is not None:
            s = s.alias(name)
    else:
        msg = "cannot initialize Series from DataFrame without any columns"
        raise TypeError(msg)

    if dtype is not None and dtype != s.dtype:
        s = s.cast(dtype, strict=strict)

    return s._s

View on GitHub (pinned to fe841f959e)