更新类别

在 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 中处理分类数据

练习时间

在 Python 中处理分类数据

Preparing Video For Download...