以 Lazy 方式轉成寬表格式
儀表板團隊需要一個以「月份 × 格式」展開的寬表檢閱次數。當你事先指定輸出欄名時,Polars 支援在 lazy 模式下使用 .pivot(),可讓整條管線從頭到尾都維持最佳化。
LazyFrame monthly_checkouts 以長表格式儲存總量,包含 month、format、total 三個欄位;而清單 formats 則包含資料中出現的每一個格式名稱。
本練習屬於課程
使用 Polars 擴充與最佳化資料管線
練習說明
- 將
monthly_checkouts進行樞紐轉換,讓每個format變成各自的欄。 - 傳入清單
formats,讓 lazy pivot 能事先知道輸出綱要。 - 將結果 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)