Last active
October 13, 2025 14:25
-
-
Save gdementen/55edd38a515b88eac47264e2f68b9b53 to your computer and use it in GitHub Desktop.
Pivot for polars LazyFrame
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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