본문 바로가기

Hotel TV Project

pandas.get_dummies (one-hot encoding)

반응형

숫자형이 아닌 컬럼들에 대해서 one-hot encoding 진행.

get_dummies를 사용하지 않을 떄,

월요일을 1, 화요일을 2, 수요일을 3이라고

단순하게 수치형 데이터로 변환하게 되면 해당 데이터들 간

1+2 = 3이라는 관계성이 존재하게 된다. 

실제로는 관계성 존재하지 않음. 따라서 학습에 잘못된 영향을 미칠 수가 있다.

 

dt['sex'][dt['sex'] == 0] = 'female'
dt['sex'][dt['sex'] == 1] = 'male'

dt['chest_pain_type'][dt['chest_pain_type'] == 1] = 'typical angina'
dt['chest_pain_type'][dt['chest_pain_type'] == 2] = 'atypical angina'
dt['chest_pain_type'][dt['chest_pain_type'] == 3] = 'non-anginal pain'
dt['chest_pain_type'][dt['chest_pain_type'] == 4] = 'asymptomatic'

dt['fasting_blood_sugar'][dt['fasting_blood_sugar'] == 0] = 'lower than 120mg/ml'
dt['fasting_blood_sugar'][dt['fasting_blood_sugar'] == 1] = 'greater than 120mg/ml'

dt['rest_ecg'][dt['rest_ecg'] == 0] = 'normal'
dt['rest_ecg'][dt['rest_ecg'] == 1] = 'ST-T wave abnormality'
dt['rest_ecg'][dt['rest_ecg'] == 2] = 'left ventricular hypertrophy'

dt['exercise_induced_angina'][dt['exercise_induced_angina'] == 0] = 'no'
dt['exercise_induced_angina'][dt['exercise_induced_angina'] == 1] = 'yes'

dt['st_slope'][dt['st_slope'] == 1] = 'upsloping'
dt['st_slope'][dt['st_slope'] == 2] = 'flat'
dt['st_slope'][dt['st_slope'] == 3] = 'downsloping'

dt['thalassemia'][dt['thalassemia'] == 1] = 'normal'
dt['thalassemia'][dt['thalassemia'] == 2] = 'fixed defect'
dt['thalassemia'][dt['thalassemia'] == 3] = 'reversable defect'

이렇게 숫자값을 string 변수로 변경 후에 

dt['sex'] = dt['sex'].astype('object')
dt['chest_pain_type'] = dt['chest_pain_type'].astype('object')
dt['fasting_blood_sugar'] = dt['fasting_blood_sugar'].astype('object')
dt['rest_ecg'] = dt['rest_ecg'].astype('object')
dt['exercise_induced_angina'] = dt['exercise_induced_angina'].astype('object')
dt['st_slope'] = dt['st_slope'].astype('object')
dt['thalassemia'] = dt['thalassemia'].astype('object')

확실하게 object로 형변환을 해준다.

 

dt = pd.get_dummies(dt, drop_first=True)

이렇게 해주면 숫자형(ex int)가 아닌 형에 대해서 one-hot encoding 처리를 해준다.

drop_first를 True로 지정하면

one-hot encoding 시에 나온 칼롬 중 첫번째 것을 제거 하는 데 

이를 테면 3가지 범주값을 3개의 칼럼을 사용해서  0 0 1, 0 1 0 ,1 0 0 으로 구분한다면 첫번째 범주 값은

0 0 1 대신 두 가지의 칼럼 값이 0 0 임을 통해 알 수 있기 때문에 줄여도 상관없음. 

반응형

'Hotel TV Project' 카테고리의 다른 글

confusion matrix (classification 평가)  (0) 2021.08.11