본문 바로가기
python

[python] 전처리

by Jasonify97 2023. 3. 10.

1. NAN값에 대하여

 

1. 평균값으로 채우기
# Age 평균 구하기
mean_age = titanic['Age'].mean()

# NaN을 평균값으로 채우기
titanic['Age'].fillna(mean_age, inplace=True)

2. 앞/뒤로 채우기
  • 시계열 데이터에서 많이 사용하는 방법
  • ffill : 앞의 값으로 채우기   
  • bfill : 뒤의 값으로 채우기

# Ozone 변수 NaN 값을 바로 앞의 값으로 채우기
air['Ozone'].fillna(method='ffill', inplace=True)

# Solar.R 변수 NaN 값을 바로 뒤의 값으로 채우기
air['Solar.R'].fillna(method='bfill', inplace=True)

3. 선형 보간법으로 채우기

 

# 선형 보간법으로 채우리
air['Ozone'].interpolate(method='linear', inplace=True)

4, nan값이 포함된 모은 행 제거
# NaN이 포함된 모든 행(axis=0) 제거
titanic.dropna(axis=0, inplace=True)

위 코드에서 subset을 사용하면 없앨 컬럼을 지정할 수 있음

# Age 변수에 NaN이 포함된 행 제거
titanic.dropna(subset=['Age'], axis=0, inplace=True)

5. knn imputer
# 선언
from sklearn.impute import KNNImputer

# model만들기, 파라미터 지정
imputer = KNNImputer(n_neighbors=2)

# 변환하기
data_filled = imputer.fit_transform(air)

# array로 나오기 때문에 dataFrame으로 바꿔줘야함
df = pd.DataFrame(data_filled)

sklearn 0.22v 이상에서 사용가능 하며, 안되면 업데이트해보기


2. 가변수화(encoding)

  • one hot encoding
  • one cold encoding(숫자가 반대로나옴)
  • label encoding
one hot encoding
titanic = pd.get_dummies(titanic, columns=dumm_cols, drop_first=True)

다중 공산성 문제로 인해 drop_first를 지정해주기

label encoding
from sklearn.preprocessing import LabelEncoder
encoder = LabelEncoder()

encoder.fit(y_train)

y_train = encoder.transform(y_train)
y_test = encoder.transform(y_test)