Lazy-Pivot ins Wide-Format
Das Dashboard-Team möchte eine breite Monatsansicht der Ausleihen nach Format. Polars unterstützt .pivot() im Lazy-Modus, wenn du die Ausgabespaltennamen im Voraus angibst. So bleibt die gesamte Pipeline von Anfang bis Ende optimiert.
Das LazyFrame monthly_checkouts enthält Summen im Long-Format mit den Spalten month, format und total, und die Liste formats enthält alle Formate im Datensatz.
Diese Übung ist Teil des Kurses
<Kurs>Skalieren und Optimieren von Data-Pipelines mit Polars</Kurs>Übungsanweisungen
- Pivotiere
monthly_checkouts, sodass jedesformatzu einer eigenen Spalte wird. - Übergib die Liste
formats, damit der Lazy-Pivot das Ausgabeschema im Voraus kennt. - Sortiere das resultierende DataFrame nach
month.
Interaktive praktische Übung
Versuche dich an dieser Übung, indem du diesen Beispielcode vervollständigst.
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)