"""
# Introduction

I prefer medium.com for writing. You can access the medium story that relevant with this notebook from [here](https://medium.com/@mebaysan/what-is-rfm-analysis-an-applied-example-in-python-1979b9853f0b). This notebook will cover just codes.

Kind regards.
"""
"""
# Loading Data
"""
import pandas as pd
from datetime import datetime
!pip install openpyxl
raw_data = pd.read_excel('../input/uci-online-retail-ii-data-set/online_retail_II.xlsx',sheet_name='Year 2010-2011')
df = raw_data.copy()
df.columns
df.head()
"""
# Drop NA
"""
df.dropna(inplace=True)
"""
# Exclude Cancelled Transactions
"""
df = df[~df['Invoice'].str.contains('C', na=False)]
"""
# Counting Total Prices
"""
df.loc[:, 'TotalPrice'] = df['Quantity'] * df['Price']
"""
# RFM Process
"""
today_date = datetime(2011, 12, 11)
rfm = df.groupby('Customer ID').agg({
    'InvoiceDate': lambda x: (today_date - x.max()).days,
    'Invoice': lambda x: x.nunique(),
    'TotalPrice': lambda x: x.sum()
})

rfm.columns = ['recency', 'frequency', 'monetary']

rfm = rfm[rfm['monetary'] > 0]
rfm.head()
"""
# Scoring RFM Metrics
"""
rfm.loc[:, 'recency_score'] = pd.qcut(rfm['recency'], 5, [5, 4, 3, 2, 1])
rfm.loc[:, 'frequency_score'] = pd.qcut(
    rfm["frequency"].rank(method="first"), 5, labels=[1, 2, 3, 4, 5])

rfm.loc[:, 'RFM_SCORE'] = rfm['recency_score'].astype(
    str) + rfm['frequency_score'].astype(str)
rfm.head()
"""
# Labelling RFM Scores
"""
seg_map = {
    r'[1-2][1-2]': 'hibernating',
    r'[1-2][3-4]': 'at_Risk',
    r'[1-2]5': 'cant_loose',
    r'3[1-2]': 'about_to_sleep',
    r'33': 'need_attention',
    r'[3-4][4-5]': 'loyal_customers',
    r'41': 'promising',
    r'51': 'new_customers',
    r'[4-5][2-3]': 'potential_loyalists',
    r'5[4-5]': 'champions'
}

rfm['segment'] = rfm['RFM_SCORE'].replace(seg_map, regex=True)
rfm.head()