更新類別

在 Python 中處理類別資料

Kasey Jones

Research Data Scientist

品種變數

品種次數統計:

dogs["breed"] = dogs["breed"].astype("category")
dogs["breed"].value_counts()
Unknown Mix                 1524
German Shepherd Dog Mix     190
Dachshund Mix               147
Labrador Retriever Mix      83
Staffordshire Terrier Mix   62
...
在 Python 中處理類別資料

重新命名類別

rename_categories 方法:

Series.cat.rename_categories(new_categories=dict)

建立字典:

my_changes = {"Unknown Mix": "Unknown"}

重新命名類別:

dogs["breed"] = dogs["breed"].cat.rename_categories(my_changes)
在 Python 中處理類別資料

更新後的品種變數

品種次數統計:

dogs["breed"].value_counts()
Unknown                     1524
German Shepherd Dog Mix     190
Dachshund Mix               147
Labrador Retriever Mix      83
Staffordshire Terrier Mix   62
...

一次進行多項變更:

my_changes = {
  old_name1: new_name1,
  old_name2: new_name2,
  ...
}
Series.cat.rename_categories(
  my_changes
)
在 Python 中處理類別資料

以函式重新命名類別

用函式批次更新類別:

dogs['sex'] = dogs['sex'].cat.rename_categories(lambda c: c.title())

dogs['sex'].cat.categories
Index(['Female', 'Male'], dtype='object')
在 Python 中處理類別資料

常見替換問題

  • 必須使用全新類別名稱
# 無效!"Unknown" 已存在
use_new_categories = {"Unknown Mix": "Unknown"}
  • 不能把兩個類別合併為一個
# 無效!新名稱必須唯一
cannot_repeat_categories = {
    "Unknown Mix": "Unknown",
    "Mixed Breed": "Unknown"
}
在 Python 中處理類別資料

合併類別:前置作業

狗的毛色:

dogs["color"] = dogs["color"].astype("category")
print(dogs["color"].cat.categories)
Index(['apricot', 'black', 'black and brown', 'black and tan',
       'black and white', 'brown', 'brown and white', 'dotted', 'golden',
       'gray', 'gray and black', 'gray and white', 'red', 'red and white',
       'sable', 'saddle back', 'spotty', 'striped', 'tricolor', 'white',
       'wild boar', 'yellow', 'yellow-brown'],
      dtype='object')
...
在 Python 中處理類別資料

合併類別範例

建立字典並使用 .replace

update_colors = {
    "black and brown": "black",
    "black and tan": "black",
    "black and white": "black",
}
dogs["main_color"] = dogs["color"].replace(update_colors)

檢查 Series 資料型別:

dogs["main_color"].dtype
dtype('O')
在 Python 中處理類別資料

轉回類別型別

dogs["main_color"] = dogs["main_color"].astype("category")
dogs["main_color"].cat.categories
Index(['apricot', 'black', 'brown', 'brown and white', 'dotted', 'golden',
       'gray', 'gray and black', 'gray and white', 'red', 'red and white',
       'sable', 'saddle back', 'spotty', 'striped', 'tricolor', 'white',
       'wild boar', 'yellow', 'yellow-brown'],
      dtype='object')
在 Python 中處理類別資料

Practice time

在 Python 中處理類別資料

Preparing Video For Download...