바뀜

둘러보기로 가기 검색하러 가기
2,213 바이트 제거됨 ,  2022년 8월 3일 (수) 10:10
1번째 줄: 1번째 줄: −
== 결측치 다루기 예시 ==
+
== 시계열에서 결측치 ==
Kaggle의 'Missing Values'에서 제공한 코드를 약간 변형.
  −
{| class="wikitable"
  −
!전략
  −
!예시
  −
|-
  −
|버리기
  −
|<syntaxhighlight lang="python">
  −
# 결측치가 하나라도 있는 열을 찾는다.
  −
cols_with_missing = [col for col in X_train.columns if X_train[col].isnull().any()]
  −
 
  −
# 해당 행 버리기.
  −
reduced_X_train = X_train.drop(cols_with_missing, axis=1)
  −
reduced_X_valid = X_valid.drop(cols_with_missing, axis=1)
  −
</syntaxhighlight>
  −
|-
  −
|채우기
  −
|<syntaxhighlight lang="python">
  −
from sklearn.impute import SimpleImputer
  −
 
  −
imputer = SimpleImputer()
  −
imputed_train_X = pd.DataFrame(imputer.fit_transform(train_X))  # 학습용 자료에 결측치 채워넣기.
  −
test_train_X = pd.DataFrame(imputer.transform(test_X))  # 테스트용 데이터에 결측치 채워넣기.(위에서 사용하는 메서드와 다르다. 무슨 차이일까..)
  −
</syntaxhighlight>[어떤 값으로 채우는 걸까?]
  −
SimpleImputer(strategy='median')
  −
 
  −
데이터프레임을 사용하는 경우, <code>fillna(채울값)</code> 함수가 준비되어 있다.
  −
 
  −
df.fillna(method = 'ffill')  # 비어 있을 경우, 바로 위 데이터를 입력
  −
 
  −
df.fillna(method = 'bfill')  # 비어 있을 경우, 바로 아래 데이터를 입력
  −
|-
  −
|채우고, 표시하기
  −
|<syntaxhighlight lang="python">
  −
X_train_plus = X_train.copy()
  −
X_valid_plus = X_valid.copy()
  −
 
  −
# 해당 값이 원랜 비어있었다는 것을 표시하기 위한 열 만들기.
  −
for col in cols_with_missing:
  −
    X_train_plus[col + '_was_missing'] = X_train_plus[col].isnull()
  −
    X_valid_plus[col + '_was_missing'] = X_valid_plus[col].isnull()
  −
 
  −
# 채우기
  −
my_imputer = SimpleImputer()
  −
imputed_X_train_plus = pd.DataFrame(my_imputer.fit_transform(X_train_plus))
  −
imputed_X_valid_plus = pd.DataFrame(my_imputer.transform(X_valid_plus))
  −
 
  −
# imputer가 열 이름을 다 지워버리기 때문에 열을 다시 복사한다.(굳이 열을 다시 살릴 이유가 있나??)
  −
imputed_X_train_plus.columns = X_train_plus.columns
  −
imputed_X_valid_plus.columns = X_valid_plus.columns
  −
</syntaxhighlight>복잡한 작업을 했기 때문에 단순 채우기보다 성능이 좋아질 것 같지만.. 오히려 나빠지는 경우도 있다.
  −
|}
  −
 
  −
= 시계열에서 결측치 =
   
자료를 지속적으로 수집하려는 시도를 하지만, 종종 에러가 발생한다든가 빼먹는 경우가 생긴다. 이럴 때 발생한 결측치는 어떻게 처리할 것인가?
 
자료를 지속적으로 수집하려는 시도를 하지만, 종종 에러가 발생한다든가 빼먹는 경우가 생긴다. 이럴 때 발생한 결측치는 어떻게 처리할 것인가?
 
+
[[분류:결측치 다루기]]
[[분류:데이터 전처리]]
 

둘러보기 메뉴