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으로 범주형 데이터 다루기