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
- Select exactly one column before converting: pl.Series(df['col']) or df.to_series().
- Check df.width before converting and handle width 0 / width > 1 explicitly.
- 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
- Check df.width == 1 before DataFrame->Series conversion.
- Convert via pl.Series(df['col']) to be explicit about which column.
- Guard df.select() results; an empty selection yields width 0.
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
- can only call '.item()' if the Series is of length 1, or an…
- can't convert to Decimal
- cannot convert List dtype to Tensor (use Array dtype…
- cannot create DataFrame from array with more than two…
- cannot select columns using key of type
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)