<jupyter_start><jupyter_text>RFM<jupyter_code>df.info()
df['InvoiceDate'] = pd.to_datetime(df['InvoiceDate'])
df.info()
df.shape
min(df['InvoiceDate'])
max(df['InvoiceDate'])
df = df.dropna()
len(df)
df['total_price'] = df['Quantity'] * df['UnitPrice']
reference_date = max(df['InvoiceDate']) + timedelta(days=1)
reference_date
df_processed = df.groupby(['CustomerID']).agg({'InvoiceDate': lambda x: (reference_date - x.max()).days,
                                              'InvoiceNo': 'count',
                                              'total_price': 'sum'})
df_processed
df_processed.columns = ['Recency', 'Frequency', 'Monetary']
df_processed.head()
import seaborn as sns

sns.distplot(df_processed['Recency'])
sns.distplot(df_processed['Frequency'])
sns.distplot(df_processed['Monetary'])
r = range(4, 0, -1)
f = range(1, 5)
m = range(1, 5)
r
for i in f:
    print(i)
r_g = pd.qcut(df_processed['Recency'], q=4, labels=r)
f_g = pd.qcut(df_processed['Frequency'], q=4, labels=f)
m_g = pd.qcut(df_processed['Monetary'], q=4, labels=m)
final_df = df_processed.assign(R = r_g.values, F = f_g.values, M = m_g.values)
final_df
def combine_rfm(x): return str(x['R']) + str(x['F']) + str(x['M'])
final_df['combined'] = final_df.apply(combine_rfm, axis=1)
rfm = final_df
rfm.head()
rfm['sum_val'] = rfm[['R', 'F', 'M']].sum(axis=1)
rfm
rfm['combined'].nunique()
def rfm_level(df):
    if df['sum_val'] >= 9:
        return 'Can\'t Loose Them'
    elif ((df['sum_val'] >= 8) and (df['sum_val'] < 9)):
        return 'Champions'
    elif ((df['sum_val'] >= 7) and (df['sum_val'] < 8)):
        return 'Loyal'
    elif ((df['sum_val'] >= 6) and (df['sum_val'] < 7)):
        return 'Potential'
    elif ((df['sum_val'] >= 5) and (df['sum_val'] < 6)):
        return 'Promising'
    elif ((df['sum_val'] >= 4) and (df['sum_val'] < 5)):
        return 'Needs Attention'
    else:
        return 'Require Activation'
rfm['rfm_level'] = rfm.apply(rfm_level, axis=1)
rfm
rfm_level_agg = rfm.groupby('rfm_level').agg({
    'Recency': 'mean',
    'Frequency': 'mean',
    'Monetary': ['mean', 'count']
}).round(1)
rfm_level_agg
rfm_level_agg.columns = rfm_level_agg.columns.droplevel()
rfm_level_agg.columns = ['Recency_Mean', 'Frequency_Mean', 'Monetary_Mean', 'Count']
rfm_level_agg
fig = plt.gcf()
ax = fig.add_subplot()
fig.set_size_inches(16, 9)
squarify.plot(sizes=rfm_level_agg['Count'], 
              label=['Can\'t Loose Them',
                     'Champions',
                     'Loyal',
                     'Needs Attention',
                     'Potential', 
                     'Promising', 
                     'Require Activation'], alpha=.6 )
plt.title('RFM Segments')
plt.axis('off')
plt.show()<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup