Skip to content

Instantly share code, notes, and snippets.

@gdementen
Last active October 13, 2025 14:25
Show Gist options
  • Save gdementen/55edd38a515b88eac47264e2f68b9b53 to your computer and use it in GitHub Desktop.
Save gdementen/55edd38a515b88eac47264e2f68b9b53 to your computer and use it in GitHub Desktop.
Pivot for polars LazyFrame
import polars as pl
def lazy_pivot(lf, on, index, values, aggregate_function=None, maintain_order=True):
on = pl.col(on)
index = pl.col(index)
values = pl.col(values)
unq_values = lf.select(on).unique(maintain_order=maintain_order).collect(engine='streaming').to_series().to_list()
if aggregate_function is None:
# FIXME: this does not replicate eager pivot default value which raises when there are several values in a cell
aggregate_function = 'first'
aggs = [
getattr(values.filter(on == value), aggregate_function)().alias(str(value))
for value in unq_values
]
return lf.group_by(index, maintain_order=maintain_order).agg(aggs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment