開始使用免費開始

將寬表轉為長表(Unpivoting)

你已經在 Spotify 資料上做了 groupby 聚合,產生了每位歌手各年份串流次數的一系列統計,並存放在 wide_df DataFrame 中。你現在想把 wide_df 轉成長表格式,方便用於資料視覺化。

本練習屬於課程

Polars 入門

檢視課程

練習說明

  • 使用 "artist""year" 作為索引欄位,以識別每一列的資料。
  • wide_df 中的統計欄位進行 unpivot:"avg_streams""max_streams""min_streams"
  • 將變數欄命名為 "metric",數值欄命名為 "stream_count"

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

long_df = (
    wide_df
    .unpivot(
        # Set the index columns
        index=____,
        # Unpivot on the stats columns
        on=____,
        # Name the variable and value columns
        variable_name=____,
        value_name=____
    )
)

print("\nLong format DataFrame:")
print(long_df)
編輯並執行程式碼