Skip to content

Instantly share code, notes, and snippets.

@ur0n2
Created February 16, 2018 14:55
Show Gist options
  • Select an option

  • Save ur0n2/a1941a0f47fb39ce6cd28abd8c75039d to your computer and use it in GitHub Desktop.

Select an option

Save ur0n2/a1941a0f47fb39ce6cd28abd8c75039d to your computer and use it in GitHub Desktop.
#-*-coding: utf-8-*-
# Index
## 1. Data Import
## 2. Data Preprocessing
## 3. Data Analysis - RFM Index Calculation
import numpy as np
import pandas as pd
import datetime
# 3. Data Analysis - RFM Index Calculation
# Recency(고객이 가장 최근에 언제 왔니) 지표 계산
## Step1 - 날짜
### 전체 고객ID와 배송 날짜(Invoice Date) 데이터를 가져와 리스트에 저장
whole_cid = list(data['CustomerID'])
invoice_dates = list(data['InvoiceDate'])
len(whole_cid), len(invoice_dates) # Print
## Step2 - 시간을 일로 변환
### 두 날짜 사이의 시간 차이를 일(days)로 표현해주는 함수를 정의
def time_delta_calculator(past_date, current_date):
delta = current_date - past_date # 두 날짜 사이의 시간 차이를 계산
return delta.days # 시간 차이를 일수(days)로 반환
### 현재 시각을 입력하고 datetime 형식으로 변환(Data가 2011년경인데 현재 2017년이라서 Gap이 큼. Recency가 너무 큼. 2012년으로 임의 설정)
current_date = '2012-01-01'
current_date = datetime.strptime(current_date, '%Y-%m-%d') #If error occured, "import datetime" or datetime.datetime.strptime()
current_date # Print
## Step3 - 각 고객의 Recency 지표 계산
### 특정 고객 ID를 가진 거래 내역 중 가자 ㅇ최근의 내역을 찾아 현재 시각(current date)과의 차이를 계산해 첨부
### 데이터베이스에 입력된 배송 날짜('InvoiceDate')이 경우 'YYYY-MM-DD HH:MM:SS' 형태이므로 이를 string으로 변환해서 인덱싱으로 활용
recency = [] # Recnecy 지표를 담을 리스트
for cid in unique_cid:
for i in range(len(whole_cid)):
if whole_cid[i] == cid:
date = str(invoice_dates[i])[:10]
date = datetime.strptime(date, '%Y-%m-%d')
days_passed = time_delta_calculator(date, current_date)
recency.append(days.passed)
break
len(recency)
recency[:10]
# Monetary 지표 계산
## 각 고객의 거래 총액 계산
### 고객 ID로 데이터를 grouping 한 다음 각 고객이 거래한 금액(TotalPrice)을 모두 합쳐(sum) 계산
monetary = data[['CUstomerID', 'TotalPrice']].goupby('CustomerID').sum()
monetary.head()
for r in recency:
if r > 25:
R.append(1)
elif r > 24:
R.append(2)
elif r > 23:
R.append(3)
else:
R.append(4)
for f in frequency:
if f < 10:
F.append(1)
elif f < 30:
F.append(2)
elif f < 50:
F.append(3)
else:
F.append(4)
for m in monetary:
if m < 1000:
M.append(1)
elif m < 2000:
M.append(2)
elif m < 3000:
M.append(3)
else:
M.append(4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment