GMARTINEZMILLA commited on
Commit
449983f
1 Parent(s): ee21747

feat: generated files

Browse files
Files changed (1) hide show
  1. app.py +53 -45
app.py CHANGED
@@ -4,126 +4,134 @@ import plotly.express as px
4
  import matplotlib.pyplot as plt
5
  import numpy as np
6
 
7
- # Configuración de la página principal
8
  st.set_page_config(page_title="Customer Insights App", page_icon=":bar_chart:")
9
 
10
- # Cargar los archivos CSV
11
  df = pd.read_csv("df_clean.csv")
12
  nombres_proveedores = pd.read_csv("nombres_proveedores.csv", sep=';')
13
 
14
  nombres_proveedores['codigo'] = nombres_proveedores['codigo'].astype(str)
15
 
16
- # Ignorar las dos últimas columnas
17
  df = df.iloc[:, :-2]
18
 
19
- # Asegurarse de que el código del cliente sea una cadena (string)
20
  df['CLIENTE'] = df['CLIENTE'].astype(str)
21
 
22
- # Función para obtener el nombre del proveedor
23
  def get_supplier_name(code):
24
  name = nombres_proveedores[nombres_proveedores['codigo'] == code]['nombre'].values
25
  return name[0] if len(name) > 0 else code
26
 
27
- # Función para crear el gráfico de radar
28
  def radar_chart(categories, values, title):
29
- # Número de variables
30
  N = len(categories)
31
 
32
- # Calcular los ángulos para cada punto
33
  angles = [n / float(N) * 2 * np.pi for n in range(N)]
34
  angles += angles[:1]
35
 
36
- # Inicializar el gráfico
37
- fig, ax = plt.subplots(figsize=(10, 10), subplot_kw=dict(projection='polar'))
38
 
39
- # Dibujar el polígono y rellenarlo
40
  values += values[:1]
41
  ax.plot(angles, values, 'o-', linewidth=2, color='#FF69B4')
42
  ax.fill(angles, values, alpha=0.25, color='#FF69B4')
43
 
44
- # Configurar los ejes
45
  ax.set_xticks(angles[:-1])
46
  ax.set_xticklabels(categories, size=8, wrap=True)
47
  ax.set_ylim(0, max(values) * 1.1)
48
 
49
- # Dibujar círculos de referencia
50
  circles = np.linspace(0, max(values), 5)
51
  for circle in circles:
52
  ax.plot(angles, [circle]*len(angles), '--', color='gray', alpha=0.3, linewidth=0.5)
53
 
54
- # Eliminar las etiquetas radiales y los bordes del gráfico
55
  ax.set_yticklabels([])
56
  ax.spines['polar'].set_visible(False)
57
 
58
- # Añadir el título
59
  plt.title(title, size=16, y=1.1)
60
 
61
  return fig
62
 
63
- # Diseño de la página principal
64
  st.title("Welcome to Customer Insights App")
65
  st.markdown("""
66
  This app helps businesses analyze customer behaviors and provide personalized recommendations based on purchase history.
67
  Use the tools below to dive deeper into your customer data.
68
  """)
69
 
70
- # Menú de navegación
71
- page = st.selectbox("Selecciona la herramienta que quieres utilizar", ["", "Customer Analysis", "Customer Recommendations"])
72
 
73
- # Página Home
74
  if page == "":
75
  st.markdown("## Welcome to the Customer Insights App")
76
  st.write("Use the dropdown menu to navigate between the different sections.")
77
 
78
- # Página Customer Analysis
79
  elif page == "Customer Analysis":
80
  st.title("Customer Analysis")
81
  st.markdown("""
82
  Use the tools below to explore your customer data.
83
  """)
84
 
85
- # Campo para filtrar clientes
86
  partial_code = st.text_input("Enter part of Customer Code (or leave empty to see all)")
87
 
88
- # Filtrar las opciones de clientes que coincidan con el código parcial
89
  if partial_code:
90
  filtered_customers = df[df['CLIENTE'].str.contains(partial_code)]
91
  else:
92
  filtered_customers = df
93
 
94
- # Crear una lista de clientes filtrados para el selectbox
95
  customer_list = filtered_customers['CLIENTE'].unique()
96
 
97
- # Selección de cliente con autocompletar filtrado
98
  customer_code = st.selectbox("Select Customer Code", customer_list)
99
 
100
  if customer_code:
101
- # Filtrar datos para el cliente seleccionado
102
  customer_data = df[df["CLIENTE"] == customer_code]
103
 
104
  if not customer_data.empty:
105
  st.write(f"### Analysis for Customer {customer_code}")
106
 
107
- # Obtener las 6 columnas con los valores más altos (ignorar la columna de cliente)
108
- top_6_manufacturers = customer_data.iloc[:, 1:].T.nlargest(6, customer_data.index[0])
109
 
110
- # Ordenar los fabricantes por valor descendente para mejor visualización
111
- top_6_manufacturers = top_6_manufacturers.sort_values(by=customer_data.index[0], ascending=False)
 
 
 
112
 
113
- # Preparar los valores y fabricantes
114
- values = top_6_manufacturers[customer_data.index[0]].values.tolist()
115
- manufacturers = [get_supplier_name(m) for m in top_6_manufacturers.index.tolist()]
116
 
117
- # Mostrar los resultados de cada fabricante
118
- st.write("### Resultados porcentaje fabricante (ordenados):")
 
 
 
 
 
119
  for manufacturer, value in zip(manufacturers, values):
120
  st.write(f"{manufacturer} = {value:.4f}")
121
 
122
- # Crear y mostrar el gráfico de radar
123
- fig = radar_chart(manufacturers, values, f'Radar Chart for Top 6 Manufacturers of Customer {customer_code}')
124
  st.pyplot(fig)
125
 
126
- # Ventas del cliente 2021-2024 (si los datos existen)
127
  if 'VENTA_2021' in df.columns and 'VENTA_2022' in df.columns and 'VENTA_2023' in df.columns and 'VENTA_2024' in df.columns:
128
  years = ['2021', '2022', '2023', '2024']
129
  sales_columns = ['VENTA_2021', 'VENTA_2022', 'VENTA_2023', 'VENTA_2024']
@@ -137,39 +145,39 @@ elif page == "Customer Analysis":
137
  else:
138
  st.warning(f"No data found for customer {customer_code}. Please check the code.")
139
 
140
- # Página Customer Recommendations
141
  elif page == "Customer Recommendations":
142
  st.title("Customer Recommendations")
143
  st.markdown("""
144
  Get tailored recommendations for your customers based on their purchasing history.
145
  """)
146
 
147
- # Campo para filtrar clientes
148
  partial_code = st.text_input("Enter part of Customer Code for Recommendations (or leave empty to see all)")
149
 
150
- # Filtrar las opciones de clientes que coincidan con el código parcial
151
  if partial_code:
152
  filtered_customers = df[df['CLIENTE'].str.contains(partial_code)]
153
  else:
154
  filtered_customers = df
155
 
156
- # Crear una lista de clientes filtrados para el selectbox
157
  customer_list = filtered_customers['CLIENTE'].unique()
158
 
159
- # Selección de cliente con autocompletar filtrado
160
  customer_code = st.selectbox("Select Customer Code for Recommendations", customer_list)
161
 
162
  if customer_code:
163
  customer_data = df[df["CLIENTE"] == customer_code]
164
 
165
  if not customer_data.empty:
166
- # Mostrar historial de compras del cliente seleccionado
167
  st.write(f"### Purchase History for Customer {customer_code}")
168
  st.write(customer_data)
169
 
170
- # Generar recomendaciones (placeholder)
171
  st.write(f"### Recommended Products for Customer {customer_code}")
172
- # Aquí puedes reemplazar con la lógica del modelo de recomendación
173
  st.write("Product A, Product B, Product C")
174
  else:
175
  st.warning(f"No data found for customer {customer_code}. Please check the code.")
 
4
  import matplotlib.pyplot as plt
5
  import numpy as np
6
 
7
+ # Page configuration
8
  st.set_page_config(page_title="Customer Insights App", page_icon=":bar_chart:")
9
 
10
+ # Load CSV files
11
  df = pd.read_csv("df_clean.csv")
12
  nombres_proveedores = pd.read_csv("nombres_proveedores.csv", sep=';')
13
 
14
  nombres_proveedores['codigo'] = nombres_proveedores['codigo'].astype(str)
15
 
16
+ # Ignore the last two columns
17
  df = df.iloc[:, :-2]
18
 
19
+ # Ensure customer code is a string
20
  df['CLIENTE'] = df['CLIENTE'].astype(str)
21
 
22
+ # Function to get supplier name
23
  def get_supplier_name(code):
24
  name = nombres_proveedores[nombres_proveedores['codigo'] == code]['nombre'].values
25
  return name[0] if len(name) > 0 else code
26
 
27
+ # Function to create radar chart
28
  def radar_chart(categories, values, title):
29
+ # Number of variables
30
  N = len(categories)
31
 
32
+ # Calculate angles for each point
33
  angles = [n / float(N) * 2 * np.pi for n in range(N)]
34
  angles += angles[:1]
35
 
36
+ # Initialize the plot
37
+ fig, ax = plt.subplots(figsize=(12, 12), subplot_kw=dict(projection='polar'))
38
 
39
+ # Draw polygon and fill it
40
  values += values[:1]
41
  ax.plot(angles, values, 'o-', linewidth=2, color='#FF69B4')
42
  ax.fill(angles, values, alpha=0.25, color='#FF69B4')
43
 
44
+ # Set axes
45
  ax.set_xticks(angles[:-1])
46
  ax.set_xticklabels(categories, size=8, wrap=True)
47
  ax.set_ylim(0, max(values) * 1.1)
48
 
49
+ # Draw reference circles
50
  circles = np.linspace(0, max(values), 5)
51
  for circle in circles:
52
  ax.plot(angles, [circle]*len(angles), '--', color='gray', alpha=0.3, linewidth=0.5)
53
 
54
+ # Remove radial labels and chart borders
55
  ax.set_yticklabels([])
56
  ax.spines['polar'].set_visible(False)
57
 
58
+ # Add title
59
  plt.title(title, size=16, y=1.1)
60
 
61
  return fig
62
 
63
+ # Main page design
64
  st.title("Welcome to Customer Insights App")
65
  st.markdown("""
66
  This app helps businesses analyze customer behaviors and provide personalized recommendations based on purchase history.
67
  Use the tools below to dive deeper into your customer data.
68
  """)
69
 
70
+ # Navigation menu
71
+ page = st.selectbox("Select the tool you want to use", ["", "Customer Analysis", "Customer Recommendations"])
72
 
73
+ # Home Page
74
  if page == "":
75
  st.markdown("## Welcome to the Customer Insights App")
76
  st.write("Use the dropdown menu to navigate between the different sections.")
77
 
78
+ # Customer Analysis Page
79
  elif page == "Customer Analysis":
80
  st.title("Customer Analysis")
81
  st.markdown("""
82
  Use the tools below to explore your customer data.
83
  """)
84
 
85
+ # Customer filter field
86
  partial_code = st.text_input("Enter part of Customer Code (or leave empty to see all)")
87
 
88
+ # Filter customer options that match the partial code
89
  if partial_code:
90
  filtered_customers = df[df['CLIENTE'].str.contains(partial_code)]
91
  else:
92
  filtered_customers = df
93
 
94
+ # Create a list of filtered customers for the selectbox
95
  customer_list = filtered_customers['CLIENTE'].unique()
96
 
97
+ # Customer selection with filtered autocomplete
98
  customer_code = st.selectbox("Select Customer Code", customer_list)
99
 
100
  if customer_code:
101
+ # Filter data for the selected customer
102
  customer_data = df[df["CLIENTE"] == customer_code]
103
 
104
  if not customer_data.empty:
105
  st.write(f"### Analysis for Customer {customer_code}")
106
 
107
+ # Define purchase threshold
108
+ purchase_threshold = 0
109
 
110
+ # Get all manufacturers the customer bought from (ignore the customer column)
111
+ all_manufacturers = customer_data.iloc[:, 1:].T[customer_data.iloc[:, 1:].T[customer_data.index[0]] > purchase_threshold]
112
+
113
+ # Sort manufacturers by value in descending order
114
+ all_manufacturers = all_manufacturers.sort_values(by=customer_data.index[0], ascending=False)
115
 
116
+ # Prepare values and manufacturers
117
+ values = all_manufacturers[customer_data.index[0]].values.tolist()
118
+ manufacturers = [get_supplier_name(m) for m in all_manufacturers.index.tolist()]
119
 
120
+ # If there are fewer than 3 manufacturers, add a third one with value 0
121
+ if len(manufacturers) < 3:
122
+ manufacturers.append("Other")
123
+ values.append(0)
124
+
125
+ # Display the results for each manufacturer
126
+ st.write(f"### Results for {len(manufacturers)} manufacturers (sorted):")
127
  for manufacturer, value in zip(manufacturers, values):
128
  st.write(f"{manufacturer} = {value:.4f}")
129
 
130
+ # Create and display the radar chart
131
+ fig = radar_chart(manufacturers, values, f'Radar Chart for {len(manufacturers)} Manufacturers of Customer {customer_code}')
132
  st.pyplot(fig)
133
 
134
+ # Customer sales 2021-2024 (if data exists)
135
  if 'VENTA_2021' in df.columns and 'VENTA_2022' in df.columns and 'VENTA_2023' in df.columns and 'VENTA_2024' in df.columns:
136
  years = ['2021', '2022', '2023', '2024']
137
  sales_columns = ['VENTA_2021', 'VENTA_2022', 'VENTA_2023', 'VENTA_2024']
 
145
  else:
146
  st.warning(f"No data found for customer {customer_code}. Please check the code.")
147
 
148
+ # Customer Recommendations Page
149
  elif page == "Customer Recommendations":
150
  st.title("Customer Recommendations")
151
  st.markdown("""
152
  Get tailored recommendations for your customers based on their purchasing history.
153
  """)
154
 
155
+ # Customer filter field
156
  partial_code = st.text_input("Enter part of Customer Code for Recommendations (or leave empty to see all)")
157
 
158
+ # Filter customer options that match the partial code
159
  if partial_code:
160
  filtered_customers = df[df['CLIENTE'].str.contains(partial_code)]
161
  else:
162
  filtered_customers = df
163
 
164
+ # Create a list of filtered customers for the selectbox
165
  customer_list = filtered_customers['CLIENTE'].unique()
166
 
167
+ # Customer selection with filtered autocomplete
168
  customer_code = st.selectbox("Select Customer Code for Recommendations", customer_list)
169
 
170
  if customer_code:
171
  customer_data = df[df["CLIENTE"] == customer_code]
172
 
173
  if not customer_data.empty:
174
+ # Show selected customer's purchase history
175
  st.write(f"### Purchase History for Customer {customer_code}")
176
  st.write(customer_data)
177
 
178
+ # Generate recommendations (placeholder)
179
  st.write(f"### Recommended Products for Customer {customer_code}")
180
+ # You can replace this with the logic of the recommendation model
181
  st.write("Product A, Product B, Product C")
182
  else:
183
  st.warning(f"No data found for customer {customer_code}. Please check the code.")