Repository navigation
Expand file tree
/
Copy pathversion5_adapter_pattern.py
More file actions
58 lines (48 loc) · 1.96 KB
/
Copy pathversion5_adapter_pattern.py
File metadata and controls
58 lines (48 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import pandas as pd
import uuid
from utils import XMLAdapter
# ↓↓↓ BUENA PRÁCTICA A LA HORA DE CREAR FUNCIONES ↓↓↓
# →→→ HACER QUE REALICEN POCAS TAREAS POR FUNCIÓN ←←←
# Creando la función 'pipeline'
def pipeline(*steps):
def wrapper(inputs):
for step in steps:
inputs = apply(step, inputs)
return inputs
return wrapper
# Formateado y filtrado
def step1(df):
df.columns = df.columns.str.lower().str.replace(" ", "_")
df = df[df["payment_method"] == "PayPal"]
df = df[df["frequency_of_purchases"].isin(["Weekly", "Fortnightly", "bi-weekly"])]
return df
# Agrupación y rankeo
def step2(df):
df = df[["customer_id", "category", "purchase_amount_(usd)"]].groupby(["customer_id", "category"]).sum().reset_index()
df["rank"] = df.groupby("category")["purchase_amount_(usd)"].rank(method="dense", ascending=False)
df = df[df["rank"] == 1]
return df
# Convertir el resultado en una lista que por dentro contiene tuplas
def step3(df):
values = df[["customer_id", "category"]].to_dict()
customers = [x for x in values["customer_id"].values()]
categories = [x for x in values["category"].values()]
result = list(zip(customers, categories))
return result
def apply(step, values):
return [step(value) for value in values]
# Cargar los datos
df1 = XMLAdapter("shopping_behavior_2023.csv").get_data()
df2 = XMLAdapter("shopping_behavior_2024.csv").get_data()
df3 = XMLAdapter("shopping_behavior_2025.csv").get_data()
# Procesar todo
p = pipeline(step1, step2, step3)
results = p([df1, df2, df3])
# Escribir cada resultado en un archivo propio
years = ["2023", "2024", "2025"]
for year, result_list in zip(years, results):
filename = f"result_{year}.txt"
with open(filename, "w") as f:
for customer_id, category in result_list:
f.write(f"{customer_id}, {category}\n")
print(f"Archivo result_{year}.txt creado con {len(result_list)} registros")