python에서 종종 data를 scaling 해야하는 경우가 존재한다. R에선 대부분 ft option으로 제공된다(더구나 default 가 scale = T 인 경우도 있는데). 그지 같은 python에선 일일이 scaling을 입혀야한다.
from sklearn.preprocessing import RobustScaler, StandardScaler, MinMaxScaler, MaxAbsScaler
from scipy.stats import yeojohnson, boxcox
values, lambda = yeojohnson(data['target'])
# values : 변환된 값
# lambda : 고유의 값, 이 값에 따라 모양이 변한다. labmda = 0인 경우 ln(x)의 형태를 따른다.
box-cox, yeo-johnson 뭘 써야할지 모른다면 그냥 yeo-johnson 사용하면 된다. 추가로 프로젝트 보고서에는 있어보이게 둘 중 고민하다가 "yeo-johnson이 좀 더 적합한 경우이기에 사용했다"고 작성하면 된다.
df.info()
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 nume1 819 non-null int64
1 nume2 819 non-null datetime64[ns]
2 cate1 819 non-null category
3 nume3 819 non-null float64
4 cate2 819 non-null category
import pandas as pd
from sklearn.preprocessing import StandardScaler
# 수치형 열 선택
numeric_columns = df.select_dtypes(include=['float64', 'int64']).columns
# StandardScaler를 사용하여 수치형 열 스케일링
transformer = StandardScaler()
df[numeric_columns] = transformer.fit_transform(df[numeric_columns])
# scaling : )
def scaling(data, scaler_option = 'standard'):
if scaler_option == 'standard':
scaler = StandardScaler()
elif scaler_option == 'robust':
scaler = RobustScaler()
elif scaler_option == 'minmax':
scaler = MinMaxScaler()
else:
raise ValueError('choose one. standard, robust, minmax')
scaled_data = pd.DataFrame(scaler.fit_transform(data), columns = data.columns).reset_index(drop = True)
return scaled_data
# 기본 옵션은 standard 로 적용된다.
# 위 파일을 .py로 저장한 뒤 from 파일이름.py import scaling 한 다음 적용하면 된다.
from 파일이름.py import scaling
scaled_data = scaling(data, 'robust')