본문 바로가기
프로덕트 분석

[Pandas] Cohort Analysis(1) 코호트 분석 시작하기

by ISLA! 2024. 1. 26.

라이브러리와 데이터 임포트

import numpy as np
import pandas as pd
import datetime as dt

import matplotlib.pyplot as plt
import seaborn as sns

from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans

import os
df = pd.read_excel('Online Retail.xlsx')

 

데이터 확인

df.head()
df.info()
df.isnull().sum()

 

결측치 제거

  • Description 과, CustomerID에 결측지 있음. 확인 필요!
df = df.dropna(subset=['CustomerID'])
df.isnull().sum().sum() 
-- 결과 : 0

 

중복 확인 및 제거

  • df.duplicated().sum() 으로 확인
# 데이터프레임의 각 행에 대해 중복 여부를 검사 > true로 반환
df.duplicated().sum()
-- 5225

df = df.drop_duplicates()
df.duplicated().sum()
-- 0

 

기술통계 확인

👉 UnitPrice의 최솟값이 0인 점, Quantity의 최솟값이 음수인 점 확인

df.describe()

df = df[(df['Quantity'] > 0) & (df['UnitPrice'] > 0)]

 

코호트 분석

  • 다음 컬럼을 생성해야 함

1. 송장 기간(Invoice period): 단일 거래/송장의 연도와 월을 문자열로 나타냄
2. 코호트 그룹(Cohort group) : 고객의 첫 구매 연도와 월을 문자열로 나타냄(특정 고객의 모든 송장에서 공통적으로 사용)
3. 코호트 기간 / 코호트 인덱스(Cohort period / Cohort Index) : 첫 구매 이후 지난 개월 수

 

  • invoiceDate에서 연, 월의 첫째날을 추출하는 함수
def get_month(x):
    return dt.datetime(x.year, x.month, 1)
    
df['InvoiceMonth'] = df['InvoiceDate'].apply(get_month)
df.head(2)

 

 

  • 고객별 처음 구매한 연/월(날짜) 도출
    • 고객아이디를 기준으로 그룹화하여, invoiceMonth 컬럼을 선택하고,
    • 각 그룹에 대해, invoiceMonth 열에서 최솟값을 찾아 CohortMonth에 할당
grouping = df.groupby('CustomerID')['InvoiceMonth']
df['CohortMonth'] = grouping.transform('min')
df.tail()

 

  • 고객별 첫 구매 월로부터 구매일까지 소요된 시간(개월 수) 계산
    • 송장일에서 연, 월, 일 도출하는 함수
    • 송장월과 코호트월에 위 함수를 적용
    • 송장연/월과 코호트 연/월 간 차이를 계산
    • CohortIndex 컬럼에 연 차이 * 12 + 월 차이 + 1 을 지정
def get_month_int(data, column):
    year = data[column].dt.year
    month = data[column].dt.month
    day = data[column].dt.day
    return year, month, day
    
    
invoice_year, invoice_month, _ = get_month_int(df, 'InvoiceMonth')
cohort_year, cohort_month, _ = get_month_int(df, 'CohortMonth')

year_diff = invoice_year - cohort_year
month_diff = invoice_month - cohort_month

df['CohortIndex'] = year_diff * 12 + month_diff + 1
df.sample(5)

 

 

  • 코호트 별로 월간 활성 고객(유저) 계산
    • 동일한 월에 가입하고, 구매까지 걸린 개월수를 기준으로 그룹화
    • 그룹별 고객 아이디의 고윳값을 계산
grouping = df.groupby(['CohortMonth', 'CohortIndex'])
cohort_data = grouping['CustomerID'].apply(pd.Series.nunique)
cohort_data = cohort_data.reset_index()
cohort_data.head(3)

 

  • 각 코호트에서 구매까지 소요된 시간 별로 활동한 고객 수
    • 위 데이터를 피봇한다. 코호트 월을 인덱스에, 구매까지 걸린 시간을 열에, 값에 고객 수를 넣는다
cohort_counts = cohort_data.pivot(index='CohortMonth', columns='CohortIndex', values='CustomerID')
cohort_counts

 

 

 

출처 : https://www.kaggle.com/code/mahmoudelfahl/cohort-analysis-customer-segmentation-with-rfm

728x90