머신러닝-전처리(변수제거, 결측치처리, 가변수화)

joooon na·2023년 8월 28일
0

머신러닝

목록 보기
1/11

0. 과정

전처리의 과정은 많지만 배운 내용에 대해서 작성해본다.
1) 불필요한 변수 제거 2) 결측치 처리 3) 가변수화

1. 불필요한 변수 제거

  • 1) target과 연관이 없거나, 2) 결측치가 많아 채울 방법이 마땅치 않은경우, 3) name과 같이 unique한 값인 경우에 변수를 제거해준다.
drop_cols = ['Cabin', 'PassengerId', 'Name', 'Ticket']
titanic.drop(drop_cols, axis=1, inplace=True)      # 1
titanic_2 =	titanic.drop(drop_cols, axis=1)		   # 2
  • 칼럼을 제거하고 커밋하는 방법은 1) inplace = True 2) titanic_2 = 과 같이 다른 변수에 집어 넣는 방법이 있다.
  • 1, 2의 방법은 혼용해서 사용하면 안된다. 만약 혼용 시, titanic_2는 받을 값이 없어서 N/A가 된다.

2. 결측치 처리

- 결측치 확인 : df.isna().sum()

#### 결측치-제거
- 1) 결측치 있는 모든 행 제거 : df.dropna(axis = 0, inplace = True)
- 2) 결측치 있는 일부 행 제거 : df.dropna(subset = ['Age'], axis = 0, inplace = True)

#### 결측치-채우기
- 1) 결측치 평균값으로 채우기 :
mean_age = titanic['Age'].mean()
titanic['Age'].fillna(mean_age, inplace=True)

- 2) 최빈값으로 채우기
titanic['Embarked'].value_counts()              #최빈값 확인 -> 'S'
titanic['Embarked'].fillna('S', inplace=True)   

- 3) 앞의 값으로 채우기
air['Ozone'].fillna(method='ffill', inplace=True)

- 4) 뒤의 값으로 채우기
air['Solar.R'].fillna(method='bfill', inplace=True)

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

3. 가변수화

- 가변수 대상 변수 식별
dumm_cols = ['Pclass', 'Sex', 'Embarked']

- 가변수화
titanic = pd.get_dummies(titanic, columns=dumm_cols, drop_first=True)
<출력>
	Pclass_2	Pclass_3	Sex_male	Embarked_Q	Embarked_S
0	0	1	1	0	1
1	0	0	0	0	0
2	0	1	0	0	1
3	0	0	0	0	1
4	0	1	1	0	1
...	...	...	...	...	...
886	1	0	1	0	1
887	0	0	0	0	1
888	0	1	0	0	1
889	0	0	1	0	0
890	0	1	1	1	0
profile
배고프다

0개의 댓글