text_html_output_1.png
from datetime import timedelta

from plotly.offline import iplot

import pandas as pd

import plotly.graph_objs as go

df = pd.read_csv('../input/flo-data2/flo_data_20k.csv')

date_columns = df.columns[df.columns.str.contains('date')]
df[date_columns] = df[date_columns].apply(pd.to_datetime)

today_date = df['last_order_date'].max() + timedelta(days=2)

rfm_df = df.groupby('master_id').agg({'last_order_date': lambda date: (today_date - date.max()).days, 'total_order_num': lambda num: num.sum(), 'total_value': lambda value: value.sum()})
rfm_df.columns = ['recency', 'frequency', 'monetary']
rfm_df['RECENCY_SCORE'] = pd.qcut(rfm_df['recency'], 5, labels=[5, 4, 3, 2, 1])
rfm_df['FREQUENCY_SCORE'] = pd.qcut(rfm_df['frequency'].rank(method='first'), 5, labels=[1, 2, 3, 4, 5])
rfm_df['MONETARY_SCORE'] = pd.qcut(rfm_df['monetary'], 5, labels=[1, 2, 3, 4, 5])
rfm_df['RF_SCORE'] = rfm_df[['RECENCY_SCORE', 'FREQUENCY_SCORE']].astype(str).apply(lambda x: ''.join(x), axis=1)
seg_map = {'[1-2][1-2]': 'hibernating', '[1-2][3-4]': 'at_risk', '[1-2]5': 'cant_loose', '3[1-2]': 'about_to_sleep', '33': 'need_attention', '[3-4][4-5]': 'loyal_customers', '41': 'promising', '51': 'new_customers', '[4-5][2-3]': 'potential_loyalists', '5[4-5]': 'champions'}
rfm_df['SEGMENT'] = rfm_df['RF_SCORE'].replace(seg_map, regex=True)

rfm_df.groupby('SEGMENT').agg({'recency': ['count', 'mean', 'min', 'max'], 'frequency': ['mean', 'min', 'max'], 'monetary': ['mean', 'min', 'max']})

def cluster_visualizer(dataframe, cluster, lim):
    trace1 = go.Bar(x=dataframe.groupby(cluster).agg({'recency': 'mean'}).reset_index()[cluster], text=round(dataframe.groupby(cluster).agg({'recency': 'mean'}).reset_index()['recency'], 2), textposition='auto', y=dataframe.groupby(cluster).agg({'recency': 'mean'}).reset_index()['recency'], name='Recency', textfont=dict(size=12), marker=dict(color='#F33F19', opacity=0.65))
    trace2 = go.Bar(x=dataframe.groupby(cluster).agg({'frequency': 'mean'}).reset_index()[cluster], text=round(dataframe.groupby(cluster).agg({'frequency': 'mean'}).reset_index()['frequency'], 2), textposition='auto', y=dataframe.groupby(cluster).agg({'frequency': 'mean'}).reset_index()['frequency'], name='Frequency', textfont=dict(size=12), marker=dict(color='#1C19F3', opacity=0.65))
    trace3 = go.Bar(x=dataframe.groupby(cluster).agg({'monetary': 'mean'}).reset_index()[cluster], text=round(dataframe.groupby(cluster).agg({'monetary': 'mean'}).reset_index()['monetary'], 2), textposition='auto', y=dataframe.groupby(cluster).agg({'monetary': 'mean'}).reset_index()['monetary'], name='Monetary', textfont=dict(size=12), marker=dict(color='#F3193D', opacity=0.65))
    trace = {'trace1': [trace1, 'Average Recency', 'Clusters', 'Recency', lim[0]], 'trace2': [trace2, 'Average Frequency', 'Clusters', 'Frequency', lim[1]], 'trace3': [trace3, 'Average Monetary', 'Clusters', 'Monetary', lim[2]]}
    for i in ['trace1', 'trace2', 'trace3']:
        layout = go.Layout(title={'text': trace[i][1], 'y': 0.9, 'x': 0.5, 'xanchor': 'center', 'yanchor': 'top'}, xaxis=dict(title=trace[i][2]), yaxis=dict(title=trace[i][3]), template='plotly_white')
        fig = go.Figure(data=[trace[i][0]], layout=layout)
        fig.update_yaxes(range=[0, trace[i][4]], automargin=True)

lim_list = [250, 15, 1500]
cluster_visualizer(rfm_df, 'SEGMENT', lim_list)

kmeans_df = df.groupby('master_id').agg({'last_order_date': lambda date: (today_date - date.max()).days, 'total_order_num': lambda num: num.sum(), 'total_value': lambda value: value.sum()})
kmeans_df.columns = ['recency', 'frequency', 'monetary']

kmeans_df.groupby('cluster').agg({'recency': ['count', 'mean', 'min', 'max'], 'frequency': ['mean', 'min', 'max'], 'monetary': ['mean', 'min', 'max']})

lim_list = [350, 10, 1000]
cluster_visualizer(kmeans_df, 'cluster', lim_list)