Question Details

No question body available.

Tags

python dataframe pivot python-polars

Answers (1)

January 22, 2026 Score: 0 Rep: 24,438 Quality: Medium Completeness: 60%

The typehint also shows a DataFrame being accepted: oncolumns: Sequence[Any] | Series | DataFrame

oncolumns = pl.DataFrame(
    [["maths", "theory"], ["maths", "practice"], ["physics", "theory"]],
    orient="row",
    schema=["subject", "exam"]
)
# shape: (3, 2)

┌─────────┬──────────┐

│ subject ┆ exam │

│ --- ┆ --- │

│ str ┆ str │

╞═════════╪══════════╡

│ maths ┆ theory │

│ maths ┆ practice │

│ physics ┆ theory │

└─────────┴──────────┘

lf.pivot(on=["subject", "exam"], index="id", oncolumns=oncolumns).collect()
# shape: (2, 4)

┌─────┬────────────────────┬──────────────────────┬──────────────────────┐

│ id ┆ {"maths","theory"} ┆ {"maths","practice"} ┆ {"physics","theory"} │

│ --- ┆ --- ┆ --- ┆ --- │

│ i64 ┆ i64 ┆ i64 ┆ i64 │

╞═════╪════════════════════╪══════════════════════╪══════════════════════╡

│ 3 ┆ null ┆ null ┆ 15 │

│ 1 ┆ 10 ┆ 12 ┆ null │

└─────┴────────────────────┴──────────────────────┴──────────────────────┘

Or in the case of your Series example .collect().to_series() would be .unnest("subject").collect() instead.