惰性透视到宽表
仪表板团队需要一个按月份 × 格式的宽表来查看借阅次数。Polars 在惰性模式下也支持 .pivot(),只要您预先指定输出列名,这样可以让整条管道从头到尾都得到优化。
惰性帧 monthly_checkouts 以长表形式保存了汇总数据,包含 month、format 和 total 三列;列表 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)