카테고리 없음
기타 전처리 기법
ParkS2
2025. 3. 1. 23:22
1. 월, 일 ,시간으로 나누기
#시계열 특성을 학습에 반영하기 위해 timestamp를 월,일,시간으로 나눈다.
train_df['year'] = train_df['timestamp'].dt.year
train_df['month'] = train_df['timestamp'].dt.month
train_df['day'] = train_df['timestamp'].dt.day
2. 연기준 일자 수 세기
# 연 기준 며칠 째인지
train_df['day_of_year'] = train_df['timestamp'].dt.dayofyear
test_df['day_of_year'] = test_df['timestamp'].dt.dayofyear
timestamp 열에서 연도 기준 몇 번째 날(day of year)인지 추출하여 day_of_year 열에 저장하는 코드
출력
train_df['day_of_year'] = 75 # 2024년 3월 15일은 1년 중 75번째 날
3. 요일 분석
# 요일 0 = monday, 6 = sunday
train_df['day_of_week'] = train_df['timestamp'].dt.dayofweek
test_df['day_of_week'] = test_df['timestamp'].dt.dayofweek
test_df의 timestamp 열에서 요일 정보를 숫자로 변환하여 (0 = 월요일, 6 = 일요일) day_of_week 열에 저장하는 코드
출력
train_df['day_of_week'] = 4 # 2024년 3월 15일은 금요일(dayofweek=4)
4.주말여부
# 주말여부
train_df['holiday'] = train_df.apply(lambda x : 0 if x['day_of_week'] < 5 else 1, axis=1)
test_df['holiday'] = test_df.apply(lambda x : 0 if x['day_of_week'] < 5 else 1, axis = 1)
평일(day_of_week < 5)이면 0, 주말(토·일, day_of_week >= 5)이면 1을 할당하는 코드
출력
train_df['holiday'] = 0 # 금요일(평일)이므로 0
train_df['holiday'] = 1 # 일요일(주말)이므로 1
5.inverse_transform
#질적 변수들을 수치화합니다
qual_col = ['item', 'corporation', 'location', 'price_mean', 'price_std', 'price_median']
for i in qual_col:
le = LabelEncoder()
train_x[i]=le.fit_transform(train_x[i])
test_x[i]=le.transform(test_x[i]) #test 데이터에 대해서 fit하는 것은 data leakage에 해당합니다
if(i == 'item'):
print(le.inverse_transform([0, 1, 2, 3, 4]))
if(i == 'location'):
print(le.inverse_transform([0,1]))
if(i == 'corporation'):
print(le.inverse_transform([0,1,2,3,4]))
print('Done.')
라벨 인코딩(Label Encoding)된 숫자를 다시 원래의 카테고리 값(문자형 데이터)으로 변환하여 해석 가능하도록