Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(python): add lazy pivot example #11325

Merged
merged 1 commit into from
Sep 26, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions py-polars/polars/dataframe/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -6871,6 +6871,9 @@ def pivot(
"""
Create a spreadsheet-style pivot table as a DataFrame.
Only available in eager mode. See "Examples" section below for how to do a
"lazy pivot" if you know the unique column values in advance.
Parameters
----------
values
Expand Down Expand Up @@ -6969,6 +6972,36 @@ def pivot(
│ b ┆ 0.964028 ┆ 0.999954 │
└──────┴──────────┴──────────┘
Note that `pivot` is only available in eager mode. If you know the unique
column values in advance, you can use :meth:`polars.LazyFrame.groupby` to
get the same result as above in lazy mode:
>>> index = pl.col("col1")
>>> columns = pl.col("col2")
>>> values = pl.col("col3")
>>> unique_column_values = ["x", "y"]
>>> aggregate_function = lambda col: col.tanh().mean()
>>> (
... df.lazy()
... .group_by(index)
... .agg(
... *[
... aggregate_function(values.filter(columns == value)).alias(value)
... for value in unique_column_values
... ]
... )
... .collect()
... ) # doctest: +IGNORE_RESULT
shape: (2, 3)
┌──────┬──────────┬──────────┐
│ col1 ┆ x ┆ y │
│ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 │
╞══════╪══════════╪══════════╡
│ a ┆ 0.998347 ┆ null │
│ b ┆ 0.964028 ┆ 0.999954 │
└──────┴──────────┴──────────┘
""" # noqa: W505
values = _expand_selectors(self, values)
index = _expand_selectors(self, index)
Expand Down
Loading