text_html_output_1.png
import datetime as dt

import pandas as pd

import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

import pandas as pd
import numpy as np
import seaborn as sns
import time, warnings
import datetime as dt
import squarify
import matplotlib.pyplot as plt
warnings.filterwarnings('ignore')
df = pd.read_csv('../input/customer-trans/data.csv', encoding='ISO-8859-1', dtype={'CustomerID': str, 'InvoiceNo': str})
df.shape

df = df[df['Country'] == 'Germany']

df['Value'] = df['Quantity'] * df['UnitPrice']
df['InvoiceDate'] = pd.DatetimeIndex(df['InvoiceDate']).date

rfm = df.groupby('CustomerID', as_index=False).agg(Recent_date=('InvoiceDate', 'max'), Frequency=('InvoiceNo', 'count'), Monetory=('Value', 'sum'))

rfm['Recency'] = rfm['Recent_date'].apply(lambda x: (dt.date(2011, 12, 31) - x).days)

rfm = rfm[['CustomerID', 'Recency', 'Frequency', 'Monetory']]

rfm['R'] = pd.qcut(rfm['Recency'], 5, labels=[5, 4, 3, 2, 1])
rfm['F'] = pd.qcut(rfm['Frequency'], 5, labels=[1, 2, 3, 4, 5])
rfm['M'] = pd.qcut(rfm['Monetory'], 5, labels=[1, 2, 3, 4, 5])
rfm['RFM_Score'] = rfm['R'].astype(str) + rfm['F'].astype(str) + rfm['M'].astype(str)

seg_map = {'[1-2][1-2]': 'Hibernating', '[1-2][3-4]': 'At Risk', '[1-2][5]': "Can't Loose", '3[1-2]': 'about to sleep', '33': 'Attention', '[3-4][4-5]': 'Loyal Customers', '41': 'Promosing', '51': 'New Customers', '[4-5][2-3]': 'Potential ', '5[4-5]': 'Champions'}
rfm['Segment'] = rfm['R'].astype(str) + rfm['F'].astype(str)
rfm['Segment'] = rfm['Segment'].replace(seg_map, regex=True)

rfm1 = rfm.groupby('Segment', as_index=False).agg(No_Cxs=('CustomerID', 'count'), Recency_mean=('Recency', 'mean'), Frequency_mean=('Frequency', 'mean'), Monetory_mean=('Monetory', 'mean')).sort_values('No_Cxs', ascending=False)
rfm1