# 전처리 및 표준화
# A. Articles detail_desc 컬럼 삭제 (결측치 삭제)
# articles 결측값 있는 컬럼(detail_desc) 제거하고 저장
articles = articles.drop(labels='detail_desc', axis=1)
# B. Club_member_stauts 탈퇴고객 삭제 (이상치 삭제)
customers = customers[customers['club_member_status'] != 'LEFT CLUB']
# C. Z-score 이용해서 표준화 진행 (transactions_price)
# Z-score 이용해서 표준화 진행 (transactions_price)
import pandas as pd
from sklearn.preprocessing import StandardScaler
# 1) z-score를 적용할 컬럼 선택
df1 = transactions[["price"]] # DataFrame 형태 유지
# 2) 표준화 진행 (평균 0, 표준편차 1)
scaler = StandardScaler()
zscore = scaler.fit_transform(df1)
# 3) 원래 값 + zscore 를 하나의 DataFrame으로 합치기
merge_df = pd.concat(
[df1.reset_index(drop=True),
pd.DataFrame(zscore, columns=["zscore"])],
axis=1
)
merge_df.columns = ["price", "zscore"]
# 4) 이상치 탐지
# 관례적으로 |z| > 3 인 값들을 이상치로 간주
mask = (merge_df["zscore"] < -3) | (merge_df["zscore"] > 3)
# 이상치만 모아보기
strange_df = merge_df[mask]
# 이상치 개수 확인, 이상치 개수: 12572
print("이상치 개수:", strange_df.shape[0])
# D. Fashion_news_frequency 결측치 fillna(“Unknown”) 처리
# customers 결측값 있는 행 fillna("Unknown")처리
customers["club_member_status"] = customers["club_member_status"].fillna("Unknown")
# articles-customers-transactions 조인 파생변수 포함 진행
df_tr_cu_inner = transactions.merge(customers, on="customer_id", how="inner")
df_full = df_tr_cu_inner.merge(articles, on="article_id", how="inner")
print("결합 후 데이터 크기:", df_full.shape)
print(df_full.head())
# 데이터가 약 20만건이 줄어든 이유
# 1. transaction에 있는데 customers에 없는 customer_id
# 2. df_tr_cu_inner에 있는데 articles에 없는 article_id
# 그럼 이 사라진 20만건은 도대체 뭐냐?
# 1. 오프라인에서 비회원 구매 데이터인가?
# 2. 상당수가 고객 또는 상품 메타 정보가 누락된 거래인가?
Python
복사
# 파생변수 생성
# 1. t_dat를 datetime으로 변환 후, year, month, weekday 파생변수 생성
# 날짜 처리
transactions["t_dat"] = pd.to_datetime(df["t_dat"])
transactions["year"] = transactions["t_dat"].dt.year
transactions["month"] = transactions["t_dat"].dt.month
transactions["weekday"] = transactions["t_dat"].dt.day_name()
# 2. age를 10단위로 그룹화 해 연령대 파생변수 생성
# 연령대 파생
customers["age_group"] = (df["age"] // 10) * 10
# 3. 고객별 평균 구매 주기 파생변수 생성
transactions["t_dat"] = pd.to_datetime(df["t_dat"])
# 고객별, 날짜순으로 정렬
transaction = transactions.sort_values(["customer_id", "t_dat"])
# 4. 같은 고객 내에서 이전 구매일과의 차이 계산
transactions["purchase_gap"] = (transactions.groupby("customer_id")["t_dat"]).diff.dt.days
# diff 이용해서 현재 이전 구매일과의 차이 계산, dt.days 이용해서 일 단위로 변환
# 5. 고객별 평균 구매 주기 계산
customer_cycle = (transactions
.groupby("customer_id")["purchase_gap"]
.mean() # 평균 구매 간격
.dropna() # 한 번만 산 고객은 제외
.reset_index() # Series 형태로 된 걸 다시 Dataframe으로 바꾸고, customer_id 일반 컬럼으로 빼기
.rename(columns={"purchase_gap": "avg_purchase_gap"}) # 컬럼 이름 지정 -> avg_purchase_gap
)
customer_cycle
# 5.1 df_full에 고객 평균 구매 주기 컬럼 붙이기
df_full = df_full.merge(customer_cycle, on="customer_id", how="left")
df_full
Python
복사
