开始使用免费开始使用

惰性透视到宽表

仪表板团队需要一个按月份 × 格式的宽表来查看借阅次数。Polars 在惰性模式下也支持 .pivot(),只要您预先指定输出列名,这样可以让整条管道从头到尾都得到优化。

惰性帧 monthly_checkouts 以长表形式保存了汇总数据,包含 monthformattotal 三列;列表 formats 列出了数据中的所有格式名称。

本练习是课程的一部分

使用 Polars 扩展与优化数据流水线

查看课程

练习说明

  • monthly_checkouts 透视,使每个 format 都成为一个独立的列。
  • 传入列表 formats,以便惰性透视预先获知输出架构。
  • 将得到的 DataFrame 按 month 排序。

交互式实操练习

通过完成这段示例代码来试试这个练习。

result = (
    monthly_checkouts
    # Pivot the format column into separate columns
    .pivot(
        on="____",
        index="month",
        values="total",
        # Pre-declare the output column names so the pivot stays lazy
        on_columns=____,
    )
    .collect()
    # Sort the wide result by month
    .sort("____")
)
print(result)
编辑并运行代码