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 turns a polars DataFrame into a Series by making a struct (width > 1) or taking the only column (width == 1). A DataFrame with zero columns has nothing to convert, so pl.Series(df) raises this TypeError instead of returning an undefined Series.

Source

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

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 df599052da)

Solutions

  1. Guard before converting: if df.width == 0: create an explicit empty Series instead.
  2. Fix the selection so at least one column remains (check df.columns before/after select).
  3. For a known dtype, fall back to pl.Series(name, [], dtype=...).

Example fix

// before
s = pl.Series(df.select(pl.all().exclude("tmp_*")))  # all columns excluded

// after
sub = df.select(pl.all().exclude("tmp_*"))
s = pl.Series(sub) if sub.width else pl.Series("struct", [], dtype=pl.Null)
Defensive patterns

Strategy: validation

Validate before calling

if df.width == 0:
    raise ValueError("cannot build Series: DataFrame has no columns")
s = pl.Series(df)

Type guard

def has_columns(df: pl.DataFrame) -> bool:
    return df.width > 0

Try / catch

try:
    s = pl.Series(df)
except TypeError as e:
    if "without any columns" in str(e):
        s = pl.Series(name or "", [], dtype=pl.Null)  # explicit empty fallback
    else:
        raise

Prevention

When it happens

Trigger: pl.Series(pl.DataFrame()); pl.Series(df.select([])); pl.Series(df.drop(df.columns)); dynamic selections like df.select(pl.all().exclude(pattern)) that exclude everything.

Common situations: Config-driven column selection where the exclusion pattern matches all columns; parsing/filtering steps earlier in the pipeline silently produced an empty frame; generic code doing pl.Series(sub_df) on user-supplied column sets.

Related errors


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