예를 들어, Color라는 열에 세 가지 색상이 있다고 가정
| Color |
|---|
| Red |
| Green |
| Blue |
원-핫 인코딩 결과
| Color_Red | Color_Green | Color_Blue |
|---|---|---|
| 1 | 0 | 0 |
| 0 | 1 | 0 |
| 0 | 0 | 1 |
pandas의 get_dummies() 함수나 sklearn.preprocessing.OneHotEncoder 클래스를 사용해 쉽게 구현할 수 있어요.
pandas의 get_dummies 함수 사용df = pd.DataFrame({'Color': ['Red', 'Green', 'Blue']})
# 원-핫 인코딩 적용
df_one_hot = pd.get_dummies(df, columns=['Color'])
print(df_one_hot)
out:
Color_Blue Color_Green Color_Red
0 0 0 1
1 0 1 0
2 1 0 0
0, 1, 2, ... 등의 정수로 매핑예)
| Color |
|---|
| Red |
| Green |
| Blue |
| Green |
레이블 인코딩하면 아래와 같이 정수로 변환
| Color | Encoded |
|---|---|
| Red | 2 |
| Green | 1 |
| Blue | 0 |
| Green | 1 |
여기서:
Blue는 0Green은 1Red는 2sklearn.preprocessing.LabelEncoder를 사용
from sklearn.preprocessing import LabelEncoder
# 예시 데이터
data = ['Red', 'Green', 'Blue', 'Green']
# LabelEncoder 생성 및 변환
le = LabelEncoder()
encoded_data = le.fit_transform(data)
print(encoded_data)
out:
[2 1 0 1]
이처럼 LabelEncoder는 각 고유한 범주를 정수로 변환해줍니다.
# 레이블 인코딩
from sklearn.preprocessing import LabelEncoder
combined = pd.concat([train,test])
cols = train.select_dtypes(include='object').columns
for col in cols:
le = LabelEncoder()
combined[col] = le.fit_transform(combined[col])
n_train = len(train)
train = combined[:n_train]
test = combined[n_train:]
concat()으로 합치는 이유는 같은 정수로 변환하기 위함LabelEncoder의 사용 시 주의 사항astype 을 통한 변환예시로 설명
train['Turbo'] = train['Engine volume'].str.contains('Turbo').astype(int)
train['Engine volume'] = train['Engine volume'].str.replace('Turbo','').astype(float)
test['Turbo'] = test['Engine volume'].str.contains('Turbo').astype(int)
test['Engine volume'] = test['Engine volume'].str.replace('Turbo','').astype(float)train['Mileage'] = train['Mileage'].str.split().str[0].astype(int)
test['Mileage'] = test['Mileage'].str.split().str[0].astype(int)
train과 test 데이터프레임에서 Engine volume과 Mileage 열의 자료형을 변경하고, Turbo라는 새로운 열을 생성하는 작업을 수행
train['Turbo'] = train['Engine volume'].str.contains('Turbo').astype(int)
test['Turbo'] = test['Engine volume'].str.contains('Turbo').astype(int)
str.contains('Turbo'): Engine volume 열에 "Turbo"라는 문자열이 포함되어 있는지 확인Engine volume이 '2.0 Turbo'라면 "Turbo" 문자열이 포함되어 있으므로 True가 반환.astype(int): True와 False 값을 각각 1과 0으로 변환"Turbo"가 포함된 경우는 1, 포함되지 않은 경우는 0으로 변환되어 Turbo 열에 저장결과적으로 Turbo 열은 Engine volume 열에 "Turbo"가 포함된 경우 1, 그렇지 않은 경우 0을 가지게 됨
train['Engine volume'] = train['Engine volume'].str.replace('Turbo','').astype(float)
test['Engine volume'] = test['Engine volume'].str.replace('Turbo','').astype(float)
str.replace('Turbo', ''): Engine volume 열에서 "Turbo" 문자열을 빈 문자열('')로 대체하여 "Turbo"를 제거'2.0 Turbo'는 '2.0'으로 변경.astype(float): 변경된 값들을 float 타입으로 변환'2.0'이 실수형 2.0으로 변환train['Mileage'] = train['Mileage'].str.split().str[0].astype(int)
test['Mileage'] = test['Mileage'].str.split().str[0].astype(int)
str.split(): Mileage 열의 각 값을 공백(' ')을 기준으로 나눔'15,000 km'라는 값은 ['15,000', 'km']로 나눔.str[0]: split() 결과에서 첫 번째 요소(숫자 부분)만 추출['15,000', 'km']에서 '15,000'만 선택.astype(int): 추출된 문자열을 정수형(int)으로 변환'15,000'이 정수형 15000으로 변환