類別
pandas 提供 category 資料型別,功能類似 R 的 factor。
你可以將欄位轉換成分類資料型別,方法是把 'category' 傳給 .astype()。一旦有了分類欄位,你可以用 .cat 存取器並查看 .categories 屬性,來檢視各種分類(在 R 中稱為「levels」)。
分類值的另一個用途是當你想在資料裡保留順序時。例如,直覺上「low」應該在「high」之前。你可以用 reorder_categories() 為某個欄位設定順序。
# 重新排序分類層級
df['column_name'].cat.reorder_categories(['low', 'high'], ordered=True)
本練習屬於課程
給 R 使用者的 Python
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Convert the type of time column
tips['time'] = ____
# Use the cat accessor to print the categories in the time column
print(____)