import pandas as pd
from collections import Counter
from google.colab import drive
drive.mount('/content/drive')
# 데이터 불러오기
df = pd.read_csv('/content/drive/MyDrive/h&m_dataset/data.csv')
# 상품별 판매량 집계
product_counts = df['prod_name'].value_counts()
# 상위 10개 상품 선택
top10 = product_counts.head(10).index.tolist()
top10_print = product_counts.head(10)
# top 10 출력
for product, count in top10_print.items():
print(f"{product} : {count}개")
# 추천 세트 저장할 리스트
bundle_sets = []
# 함수: 연관 상품 찾기
def find_bundle(base_product):
# 해당 상품 구매자 ID 목록
buyers = df[df['prod_name'] == base_product]['customer_id'].unique()
# 그 사람들이 산 다른 상품
other = df[
(df['customer_id'].isin(buyers)) &
(df['prod_name'] != base_product)
]
counter = Counter(other['prod_name'])
if counter:
best_match, match_count = counter.most_common(1)[0]
else:
best_match, match_count = None, 0
return best_match, match_count
# 루프 돌면서 base 상품과 연관 상품 + 판매량 함께 저장
used_products = set() # 이미 세트에 사용된 상품 추적용
for base in top10:
base_count = product_counts[base]
if base in used_products:
continue # 이미 세트에 포함된 상품은 스킵
# base 상품을 산 고객들
buyers = df[df['prod_name'] == base]['customer_id'].unique()
# 그 고객들이 산 다른 상품 (base 제외, used 제외)
other = df[
(df['customer_id'].isin(buyers)) &
(df['prod_name'] != base) &
(~df['prod_name'].isin(used_products))
]
counter = Counter(other['prod_name'])
if counter:
bundle_product, bundle_count = counter.most_common(1)[0]
else:
bundle_product, bundle_count = None, 0
bundle_sets.append({
'base_product': base,
'base_count': base_count,
'bundle_product': bundle_product,
'bundle_count': bundle_count
})
# 사용된 상품 등록
used_products.add(base)
if bundle_product:
used_products.add(bundle_product)
# 출력
for row in bundle_sets:
print(f"{row['base_product']} ({row['base_count']}개 팔림) → {row['bundle_product']} ({row['bundle_count']}개 팔림)")
# FN + Active 모두 동의한 유저만 추출
df_agree = df[(df['FN'] == 1) & (df['Active'] == 1)].copy()
# 나이대 생성
df_agree['age_group'] = (df_agree['age'] // 10 * 10).astype(int)
df_agree = df_agree[df_agree['age_group'].between(10, 90)]
# 날짜 변환 + 계절 생성
df_agree['t_dat'] = pd.to_datetime(df_agree['t_dat'])
def get_season(month):
if month in [3, 4, 5]: return '봄'
elif month in [6, 7, 8]: return '여름'
elif month in [9, 10, 11]: return '가을'
else: return '겨울'
df_agree['season'] = df_agree['t_dat'].dt.month.apply(get_season)
# 결과 저장
results = []
# 나이대, 계절 조합별 Top5 상품코드 + 판매량
for age in range(10, 100, 10):
for season in ['봄', '여름', '가을', '겨울']:
subset = df_agree[(df_agree['age_group'] == age) & (df_agree['season'] == season)]
vc = subset['product_code'].value_counts().head(5)
top5 = list(zip(vc.index.tolist(), vc.values.tolist())) # (코드, 수량)
results.append({
'나이대': f"{age}대",
'계절': season,
'Top5': top5
})
# 출력
for row in results:
print(f"{row['나이대']} {row['계절']} Top5 상품코드:")
for code, count in row['Top5']:
print(f"- {code} ({count}개)")
print()