0% found this document useful (0 votes)
54 views9 pages

PC2. Bernal Leandro, Melissa

The document describes a program that performs customer segmentation and lifetime value analysis on transactional data. It includes the following key steps: 1. Import necessary libraries and read in transaction data. 2. Calculate recency, frequency, and monetary (revenue) scores by customer and cluster customers into groups for each metric. 3. Analyze how outliers influence cluster formation and determine the optimal number of clusters. 4. Provide descriptive statistics that show the VVC cluster with the most recent customers has the lowest average revenue, while the cluster with most frequent, long-term customers has the highest average revenue.

Uploaded by

Diego Vega
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views9 pages

PC2. Bernal Leandro, Melissa

The document describes a program that performs customer segmentation and lifetime value analysis on transactional data. It includes the following key steps: 1. Import necessary libraries and read in transaction data. 2. Calculate recency, frequency, and monetary (revenue) scores by customer and cluster customers into groups for each metric. 3. Analyze how outliers influence cluster formation and determine the optimal number of clusters. 4. Provide descriptive statistics that show the VVC cluster with the most recent customers has the lowest average revenue, while the cluster with most frequent, long-term customers has the highest average revenue.

Uploaded by

Diego Vega
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

I PROGRAMA: ANALISTA DE DATOS DE NEGOCIOS – MODALIDAD

VIRTUAL

CLIENT PROFITABILITY ANALYTICS


Segunda Práctica Calificada

Alumno: Melissa Lesly Bernal Leandro


Email: [email protected]
Fecha: 12 abril de 2021
ACTIVIDAD 1
Enunciado: Mostrar procedimiento desarrollado en un solo programa.
# Parte A
import pandas as pd
import numpy as np
import sys
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
def order_cluster(cluster_field_name, target_field_name,df,ascending):
new_cluster_field_name = 'new_' + cluster_field_name
df_new =
df.groupby(cluster_field_name)[target_field_name].mean().reset_index()
df_new =
df_new.sort_values(by=target_field_name,ascending=ascending).reset_index(dr
op=True)
df_new['index'] = df_new.index
df_final = pd.merge(df,df_new[[cluster_field_name,'index']],
on=cluster_field_name)
df_final = df_final.drop([cluster_field_name],axis=1)
df_final = df_final.rename(columns={"index":cluster_field_name})
return df_final
# Parte B
tx_data = pd.read_csv('./data/customer_segmentation.csv', encoding='cp1252')
tx_data['InvoiceDate'] = pd.to_datetime(tx_data['InvoiceDate'])
tx_data['InvoiceYearMonth'] = tx_data['InvoiceDate'].map(lambda date:
100*date.year + date.month)
tx_uk = tx_data.query("Country=='United Kingdom'").reset_index(drop=True)
# Parte C
tx_user = pd.DataFrame(tx_data['CustomerID'].unique())
tx_user.columns = ['CustomerID']
# Parte D
tx_max_purchase =
tx_uk.groupby('CustomerID').InvoiceDate.max().reset_index()
tx_max_purchase.columns = ['CustomerID','MaxPurchaseDate']
tx_max_purchase['Recency'] = (tx_max_purchase['MaxPurchaseDate'].max() -
tx_max_purchase['MaxPurchaseDate']).dt.days
tx_user = pd.merge(tx_user, tx_max_purchase[['CustomerID','Recency']],
on='CustomerID')
kmeans = KMeans(n_clusters=4)
tx_user['RecencyCluster'] = kmeans.fit_predict(tx_user[['Recency']])
tx_user = order_cluster('RecencyCluster', 'Recency',tx_user,False)
# Parte E
tx_frequency = tx_uk.groupby('CustomerID').InvoiceDate.count().reset_index()
tx_frequency.columns = ['CustomerID','Frequency']
tx_user = pd.merge(tx_user, tx_frequency, on='CustomerID')
kmeans=KMeans(n_clusters=4)
tx_user['FrequencyCluster']=kmeans.fit_predict(tx_user[['Frequency']])
tx_user = order_cluster('FrequencyCluster', 'Frequency', tx_user, True )
# Parte F
tx_uk['Revenue'] = tx_uk['UnitPrice'] * tx_uk['Quantity']
tx_revenue = tx_uk.groupby('CustomerID').Revenue.sum().reset_index()
tx_user = pd.merge(tx_user, tx_revenue, on='CustomerID')
#tx_user = tx_user[tx_user['Revenue']<tx_user['Revenue'].quantile(0.98)]
kmeans = KMeans(n_clusters=4)
tx_user['RevenueCluster'] = kmeans.fit_predict(tx_user[['Revenue']])
tx_user = order_cluster('RevenueCluster', 'Revenue',tx_user,True)
# Parte G
kmeans = KMeans(n_clusters=4)
tx_user['VVCCluster'] = kmeans.fit_predict(tx_user[['RecencyCluster',
'FrequencyCluster','RevenueCluster']])
# Parte H G
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = np.array(tx_user['RecencyCluster'])
y = np.array(tx_user['FrequencyCluster'])
z = np.array(tx_user['RevenueCluster'])
ax.set_title("Valor de Vida de los Clientes")
ax.set_xlabel("RecencyCluster")
ax.set_ylabel("FrequencyCluster")
ax.set_zlabel("RevenueCluster")
ax.scatter(x,y,z, marker="s", c=tx_user["VVCCluster"], s=40, cmap="RdBu")
plt.show()
ACTIVIDAD 2
Enunciado: Explicación del desarrollo del programa.
# Parte A: Se importa las librerías necesarias para el funcionamiento del
programa

# Parte B: Se lee la data y se procede a su creación respectiva

# Parte C: Se crea una dataframe genérico para capturar el CustomerID y


nuevos escores de segmentación

# Parte D: Se calcula Recency


# Se calcula la fecha máxima de compra por cada cliente

# Se compara la fecha de la última transacción por cada cliente

# Se pasa estos datos a tx_user

# Se construye 4 grupos para recency y se adiciona a tx_user

# Se ordena los grupos


Resultado gráfico

# Parte E : Se calcula Frecuencia


# Se calcula el número de transacciones por cada cliente

# Se pasa estos datos a tx_user

# Se construye 4 grupos para frecuencia y adiciona a tx_user

# Se ordena por la frecuencia del cluster

Resultado gráfico:

# Parte F : Se calcula Revenue


# Se calcula el ingreso por cada cliente
# Se pasa estos datos a tx_user

# Se construye 4 grupos y adiciona a tx_user

# Se ordena

Resultado gráfico:
ACTIVDAD 3
Enunciado: Analizar la influencia de los valores extremos en la formación de
los grupos.
Recency

Antes Después

Frecuencia

Antes Después

Revenue

Antes Después

En los tres casos mostrados se puede apreciar los valores extremos mínimos y
máximos son suavizados para una mejor representación de los resultados.
ACTIVIDAD 4
Enunciado: Determinar la cantidad de grupos VVC apropiado.
4 grupos

20 grupos

100 grupos

Como se puede observar conforme se cuente con más grupos los datos
graficados incrementan en volumen y su ubicación en cercanía.
• Para RecencyCluster se tiene los siguientes valores:

count mean std min 25% 50% 75% max


VVCCluster
0 1046 0.543021 0.498384 0 0 1 1 1
1 1532 3 0 3 3 3 3 3
2 950 2 0 2 2 2 2 2
3 422 2.990521 0.097011 2 3 3 3 3

Se tiene el mayor valor recency para el VVCcluster 1 (más tiempo) y el menor


valor para el VVCcluster 0 (más reciente).

• Para FrecuencyCluster se tiene los siguientes valores:


count mean std min 25% 50% 75% max
VVCCluster
0 1046 0.007648 0.08716 0 0 0 0 1
1 1532 0 0 0 0 0 0 0
2 950 0.032632 0.177764 0 0 0 0 1
3 422 1.049763 0.308066 0 1 1 1 3

Se tiene el mayor valor frecuencia para el VVCcluster 3 y el menor valor para el


VVCcluster 1.

• Para RevenueCluster se tiene los siguientes valores:


count mean std min 25% 50% 75% max
VVCCluster
0 1046 0.005736 0.075556 0 0 0 0 1
1 1532 0.039817 0.195593 0 0 0 0 1
2 950 0.009474 0.096922 0 0 0 0 1
3 422 0.516588 0.638034 0 0 0 1 3

Se tiene el mayor valor revenue para el VVCcluster 3 y el menor valor para el


VVCcluster 0.

VVCCluster Cantidad % total Se puede apreciar que el grupo que más


0 1046 26% reciente ha operado con la empresa en el
1 1532 39%
VVCc 0 (26% del total de empresas), sin
2 950 24%
3 422 11% embargo, este grupo representa el menor
TOTAL 3950 100% revenue (promedio 0.57%). De la misma
manera, el mayor valor revenue corresponde al grupo VVCc 3 (promedio
51.66%), además cuentan con el mayor de valor frecuencia, este grupo
representa el 11% del total de empresas.

You might also like