使用視窗函式以多個欄位分組
為了更深入分析,你想同時依照一天中的時段與天氣來拆解腳踏車需求。溫暖晴朗的時段很可能與涼爽多雲的時段表現不同。請先建立一個簡單的天氣類別,接著計算各「小時 × 天氣」組合的租借總數。
已將 polars 載入為 pl。提供的 DataFrame bikes 具有 time、rentals、temp 與 hour 欄位。
本練習屬於課程
使用 Polars 進行資料轉換
練習說明
- 建立
weather欄位:當temp大於 20 時為"warm",否則為"cool"。 - 新增
total_by_hour_weather欄位,內容為依hour與weather分組後的rentals加總。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Add weather category based on temperature
bikes.with_columns(
pl.when(pl.col("temp") > 20)
.then(pl.lit("____"))
.otherwise(pl.lit("____"))
.alias("weather")
).with_columns(
# Calculate total rentals by hour and weather
pl.col("rentals").____().over("____", "____").alias("total_by_hour_weather")
)