수영장의 수영_데이터 분석 블로그

[빅분기 실기] 작업형 제2유형 - 전처리 종합코드 본문

자격증/빅데이터분석기사

[빅분기 실기] 작업형 제2유형 - 전처리 종합코드

슈빔멘 2021. 12. 2. 22:13

그대로 암기해갈 코드를 정리해볼 것이다

2일의 기적..

 

 

# 라이브러리 

import pandas as pd
import numpy as np

# 데이터 불러오기 (생략)
X_train.shape, y_train.shape, X_test.shape

일단 데이터를 받아와서 형태를 본다

 

# 기본 정보 확인
X_train.head()
y_train.value_counts()
X_train.info()

# 결측치
X_train.isnull().sum()
X_test.isnull().sum()

# 기술통계
X_train.describe()

데이터셋을 탐색한다

데이터 구조나 빠진 값, 평균, 최대최소 등등

# 결측치 처리

X_train.isnull().sum()
X_test.isnull().sum()

# 1. 0으로 채우기
X_train['환불금액'] = X_train['환불금액'].fillna(0)
X_test['환불금액'] = X_test['환불금액'].fillna(0) 

# 2. 해당 열 삭제하기
X_train = X_train.drop('열 이름', axis=1)
X_test = X_test.drop('열 이름', axis=1)
# 이상치 개수 확인
len(X_train[X_train['열 이름'] == '조건'])
# ex)
len(X_train[X_train['평균수입'] < 0 ])

# 이상치 삭제
del_index = X_train[(X_train['평균수입'] <0 )].index
X_train = X_train.drop(index = del_index, axis = 0)
y_train = y_train.drop(index = del_index, axis =0)

# 이상치 대체
cols = ['나이','키','몸무게']
cols_mean = X_train.cols.mean()
X_train[cols].replace(0, cols_mean)

결측치랑 이상치 처리하는 법

기억안나면 그냥,,,, 결측치만 drop할 예정

 

# Scaling

from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
cols = ['열1','열2', '열3'] ## 주의 : 수치형 변수 열만 넣어야함!! 당연함

X_train[cols] = scaler.fit_transform(X_train[cols])
X_test[cols] = scaler.fit_transform(X_test[cols])

스케일링,,, 몇줄안되니까 외워갈라고

근데 스케일링 유무에 따라 성능이 많이 달라지진 않음

 

 

 

# 문자열로 입력된 날짜 -> 날짜형 변환
# 년/월/일 분할

def datePreprocessing(df2):
    
    df =df2.copy()
    df['일자'] = pd.to_datetime(df['일자'])
    df['년도'] = df['일자'].dt.year
    df['월'] = df['일자'].dt.month
    df['일'] = df['일자'].dt.day
    df['weekend'] = df['일자'].dt.weekday    
    
    
    return df

pre_train = datePreprocessing(train_X).drop(['일자','id'],axis=1)
pre_test = datePreprocessing(test_X).drop(['일자','id'],axis=1)