該讀書囉,Katniss!
快要到收工時間了。不過在此之前,你想做個好玩的分析。這次你要分析另一個書籍資料集,主題是《飢餓遊戲》系列。
你在重塑之前已經先看過 books_hunger 資料集,但哪裡怪怪的:這個 DataFrame 的索引放的是書名。你知道這種格式沒辦法直接做重塑。如果硬做,你會失去很重要的資料——書名。為了避免這個問題,你需要先做些調整,再把 DataFrame 轉換格式。
books_hunger 資料集已經為你準備好。它包含 title,以及每本書的 language、publication date、publication number、page number 等資訊。
本練習屬於課程
使用 pandas 重塑資料
練習說明
- 將
books_hunger的索引重設,但不要把它丟棄。 - 將
books_hunger從寬格式轉為長格式。使用title與language作為唯一索引。把由欄位(以publication與page開頭)所建立的新變數命名為feature。這些欄位以空白分隔,並以一個單字結尾。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Modify books_hunger by resetting the index without dropping it
books_hunger.____(____=____, inplace=____)
# Reshape using title and language as index, feature as new name, publication and page as prefix separated by space and ending in a word
publication_features = pd.wide_to_long(____,
____=____,
____=____,
____=____,
____=____,
____=____)
# Print publication_features
print(publication_features)