<jupyter_start><jupyter_text>Customer Segmentation Cohort Analyse<jupyter_code>import numpy as np
import pandas as pd
import os
import datetime as dt
import seaborn as sns
import matplotlib.pyplot as plt<jupyter_output><empty_output><jupyter_text>Dataset**[UCI Maschine Learning Repository](https://archive.ics.uci.edu/ml/datasets/Online%20Retail)**<jupyter_code>print(os.getcwd())
#online = pd.read_excel('../data/Online Retail.xlsx')<jupyter_output>/home/hans/python_codes/DataCamp/customer_segmentation<jupyter_text>- Top 5 rows of data<jupyter_code>online.head(5)<jupyter_output><empty_output><jupyter_text>Assign acquisition month cohort<jupyter_code>def get_month(x): return dt.datetime(x.year, x.month, 1)

online['InvoiceMonth'] = online['InvoiceDate'].apply(get_month)
grouping = online.groupby('CustomerID')['InvoiceMonth']
online['CohortMonth'] = grouping.transform('min')
online.head()<jupyter_output><empty_output><jupyter_text>Extract integer values from data> Define function to extract year , month and day integer values.> We will use it throughout the course.<jupyter_code>def get_date_int(df, column):
    year = df[column].dt.year
    month = df[column].dt.month
    day = df[column].dt.day
    return year, month, day<jupyter_output><empty_output><jupyter_text>Assign time offset value<jupyter_code>invoice_year, invoice_month, _ = get_date_int(online, 'InvoiceMonth')
cohort_year, cohort_month, _ = get_date_int(online, 'CohortMonth')

years_diff = invoice_year - cohort_year
months_diff = invoice_month - cohort_month

online['CohortIndex'] = years_diff * 12 + months_diff + 1
online.head(5)<jupyter_output><empty_output><jupyter_text>Count monthly active customers from each cohort<jupyter_code>grouping = online.groupby(['CohortMonth', 'CohortIndex'])
cohort_data = grouping['CustomerID'].apply(pd.Series.nunique)
cohort_data = cohort_data.reset_index()
cohort_counts = cohort_data.pivot(index='CohortMonth',
    columns='CohortIndex',
    values='CustomerID')<jupyter_output><empty_output><jupyter_text>Calculate cohort metrics  Customer retention: cohort_counts table - How many customers originally in each cohort? (Column 1)- How many of them were active in following months? (Column 2-13)<jupyter_code>cohort_counts.head()<jupyter_output><empty_output><jupyter_text>Calculate Retention rate - Store the first column as cohort_sizes<jupyter_code>cohort_sizes = cohort_counts.iloc[:,0]<jupyter_output><empty_output><jupyter_text>- Divide all values in the cohort_counts table by cohort_sizes<jupyter_code>retention = cohort_counts.divide(cohort_sizes, axis=0)<jupyter_output><empty_output><jupyter_text>- Review the retention table  Retention table<jupyter_code>retention.round(3) * 100<jupyter_output><empty_output><jupyter_text>Other metrics<jupyter_code>grouping = online.groupby(['CohortMonth', 'CohortIndex'])
cohort_data = grouping['Quantity'].mean()
cohort_data = cohort_data.reset_index()
average_quantity = cohort_data.pivot(index='CohortMonth',
columns='CohortIndex',
values='Quantity')<jupyter_output><empty_output><jupyter_text>Average quantity for each cohort<jupyter_code>average_quantity.round(1)<jupyter_output><empty_output><jupyter_text>Cohort analysis visualization - Build the heatmap<jupyter_code>import seaborn as sns
import matplotlib.pyplot as plt

plt.figure(figsize=(10, 8))
plt.title('Retention rates')
sns.heatmap(data = retention,
annot = True,
fmt = '.0%',
vmin = 0.0,
vmax = 0.5,
cmap = 'BuGn')

plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11759656652360514, 'fraction_numerical': 0.008011444921316165, 'mean_word_length': 8.68421052631579, 'pattern_counts': {'":': 0, '<': 56, '<?xml version=': 0, '>': 58, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '14', 'dir': 'jupyter-structured-clean-dedup', 'id': '440837', 'license': 'MIT', 'n_tokens_mistral': 1305, 'n_tokens_neox': 1208, 'n_words': 219, 'path': 'customer_segmentation/01_customer_segmentation.ipynb', 'repo_name': 'hanshof/ml_tutorials', 'size': '3495'}