# 필요한 패키지들
import pandas as pd
import numpy as np
# 간단한 EDA
import matplotlib.pyplot as plt
import seaborn as sns
# 통계 관련 부분
import scipy.stats as stats
# 데이터 처리
from sklearn.model_selection import train_test_split
# 데이터 로드
train_path = "train.csv"
test_path = "test.csv"
train_df = pd.read_csv(train_path)
test_df = pd.read_csv(test_path)
# 데이터 확인
train_df.head()
test_df.head()
# 이상치 확인
sns.lmplot(data=train_df, x="GrLivArea", y="SalePrice")
# 2. 수치형 컬럼들의 결측치를 0으로 채우기
zeros = ['GarageYrBlt', 'GarageArea', 'GarageCars', 'BsmtFinSF1', 'BsmtFinSF2',
'BsmtUnfSF', 'TotalBsmtSF', 'BsmtFullBath', 'BsmtHalfBath', 'MasVnrArea']
for col in zeros:
train_df[col].fillna(0, inplace=True)
test_df[col].fillna(0, inplace=True)
# Utilities -> test에서 누락이 되어 있는 컬럼이지만, 전혀 변화가 없는 컬럼이므로 제거의 대상이다.
train_df.drop("Utilities", axis=1, inplace=True)
test_df.drop("Utilities", axis=1, inplace=True)
freq = ['MSZoning', 'Exterior1st', 'Exterior2nd', 'SaleType',
'Electrical', 'KitchenQual', 'Functional']
for col in freq:
train_df[col].fillna(train_df["MSZoning"].mode()[0], inplace=True)
test_df[col].fillna(train_df["MSZoning"].mode()[0], inplace=True)
# 결측치 제거 여부 확인
print(train_df.isnull().sum().sum())
print(test_df.isnull().sum().sum())
📌 인코딩
# 라벨 인코딩
from sklearn.preprocessing import LabelEncoder
ordinals = ['LotShape', 'LandSlope', 'OverallQual', 'OverallCond', 'ExterQual', 'ExterCond', 'BsmtQual',
'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2', 'HeatingQC', 'Electrical', 'KitchenQual',
'Functional', 'FireplaceQu', 'GarageFinish', 'GarageQual', 'GarageCond', 'PavedDrive', 'PoolQC', 'Fence']
for col in ordinals:
le = LabelEncoder()
# 컬럼값의 종류에 따른 규칙 학습
le.fit(train_df[col])
# train_df에 train_df의 컬럼에서 학습한 룰 대로 변환 : A->0, B->1, C->2
train_df[col] = le.transform(train_df[col])
# 1.기존의 룰을 바탕으로 test에서의 unseen data에 대한 룰을 추가
# 2.test에 갱신된 신규 룰을 test에 적용
# train의 학습된 규칙을 그대로 가지고 옴
prev_class = list(le.classes_)
# unseen data인지 체크
for label in np.unique(test_df[col]):
if label not in prev_class: # unseen data
prev_class.append(label)
le.classes_= np.array(prev_class)
# test에 적용해서 변환
test_df[col] = le.transform(test_df[col])
cat_dummies = [col for col in train_df if "_" in col and col.split("_")[0] in nominals]
# 1) train에만 존재하고 test에는 없는 경우, test에 컬럼 추가 & 0으로 채우기
for col in cat_dummies:
if col not in test_df.columns:
print("컬럼추가: ", col)
test_df[col] = 0
# 2) test에서 train에서는 보지 못한 unseen 데이터 처리
for col in test_df.columns:
if ("_" in col) and (col.split("_")[0] in nominals) and (col not in cat_dummies):
print("제거된 컬럼: ", col)
test_df.drop(col, axis=1, inplace=True)