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
...
rename_categories メソッド:
Series.cat.rename_categories(new_categories=dict)
辞書を作成:
my_changes = {"Unknown Mix": "Unknown"}
カテゴリ名を変更:
dogs["breed"] = dogs["breed"].cat.rename_categories(my_changes)
品種の出現回数:
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
)
複数カテゴリを一括更新:
dogs['sex'] = dogs['sex'].cat.rename_categories(lambda c: c.title())dogs['sex'].cat.categories
Index(['Female', 'Male'], dtype='object')
# 動きません! "Unknown" は既に存在
use_new_categories = {"Unknown Mix": "Unknown"}
# 動きません! 新しい名前は一意である必要あり
cannot_repeat_categories = {
"Unknown Mix": "Unknown",
"Mixed Breed": "Unknown"
}
犬の色:
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')
...
辞書を作り、.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')
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でカテゴリカルデータを扱う