범주 업데이트

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...