Skip to content

Commit

Permalink
docs(python): add lazy pivot example (pola-rs#11325)
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcoGorelli authored and Romano Vacca committed Oct 1, 2023
1 parent e2711aa commit 6c9d7bd
Showing 1 changed file with 33 additions and 0 deletions.
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

0 comments on commit 6c9d7bd

Please sign in to comment.