# A veces necesitamos instalar nuevas librerías en nuestros proyectos
# "!" para instalar librería desde el intérprete...sino se instala desde la consola
!pip install openpyxl==3.0.10
#luego no hace falta importarla
Collecting openpyxl==3.0.10
Downloading openpyxl-3.0.10-py2.py3-none-any.whl (242 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 242.1/242.1 KB 29.8 MB/s eta 0:00:00
Collecting et-xmlfile
Downloading et_xmlfile-1.1.0-py3-none-any.whl (4.7 kB)
Installing collected packages: et-xmlfile, openpyxl
Successfully installed et-xmlfile-1.1.0 openpyxl-3.0.10
WARNING: You are using pip version 22.0.4; however, version 22.1.2 is available.
You should consider upgrading via the '/root/venv/bin/python -m pip install --upgrade pip' command.
# imports
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import sqlite3 as sql3
import seaborn as sns
# Levanto los datos en 3 diferentes dataframes
# ARTÍCULOS
#Creo una conexion y le digo la fuente de los datos
con = sql3.connect("/work/data/articles.db")
#pandas tiene un método para leer los querys de sql
sql_query = pd.read_sql_query("SELECT * FROM articles", con) ###VER INDEX_COL DEL DF_SELLERS
#creo el Data frame
df_articles = pd.DataFrame(sql_query, columns= ["article_id", "article_name", "unit_price"])
print(df_articles)
article_id article_name unit_price
0 20015 Smartphone 525.00
1 20016 Full Pc 2127.81
2 20017 Monitor 230.00
3 20018 Tablet 130.00
4 20019 Desk 130.10
5 20020 Chair 335.64
6 20021 Modem 67.50
7 20022 Range Extender 20.45
8 20023 Notebook 1000.00
9 20024 Netbook 145.00
10 20025 HDD 54.62
11 20026 SDD 22.00
12 20027 Ram Memory 35.95
13 20028 Motherboard 138.38
14 20029 Mouse 30.30
15 20030 Fan Cooler 4.25
16 20031 Webcam 20.07
17 20032 Keyboard 22.60
18 20033 Headphones 23.30
19 20034 Scanner 185.00
20 20035 Case 37.90
21 20036 Video Card 131.50
22 20037 CPU 139.62
23 20038 Power Supply 43.95
24 20039 Water Cooling 67.50
25 20040 Heatsink 10.00
26 20041 Usb Cable 2.95
27 20042 Sata Cable 2.14
28 20043 Pci Express Port 10.12
29 20044 Wi-Fi Card 59.61
30 20045 Mesh Wi-Fi X 2 32.50
#VENDEDORES
#creo el df de vendedores
df_sellers = pd.read_excel("/work/data/sellers.xlsx", index_col= 0) #con index elegí cuál quiero que sea mí índice
print(df_sellers)
seller_name
seller_id
1 Aveline Swanwick
2 Jase Doy
3 Oliviero Charkham
4 Cornie Wynrehame
5 Ewell Peres
6 Milly Christoffe
7 Kati Innot
8 Tobin Roselli
9 Onida Cosely
10 Cirilo Grandham
11 Vasily Danilyuk
12 Brockie Patience
13 Arnold Kilkenny
14 Janel O'Curran
15 Daisie Slograve
#ÓRDENES
df_orders = pd.read_csv("/work/data/orders.csv")
print(df_orders)
order_id week article_id quantity seller_id country_name
0 15024 1 20039 10 10 Peru
1 15025 1 20029 15 5 Peru
2 15026 1 20024 5 14 Bolivia
3 15027 1 20018 9 14 Brazil
4 15028 1 20035 6 15 Mexico
.. ... ... ... ... ... ...
995 16019 4 20021 1 7 Brazil
996 16020 4 20040 15 15 Brazil
997 16021 4 20040 2 11 Colombia
998 16022 4 20018 14 11 Brazil
999 16023 4 20026 12 9 Brazil
[1000 rows x 6 columns]
# Exploración del df de artículos
print("Muestra de datos")
print(df_articles.head())
print("\nFormato del dataframe")
print(df_articles.shape)
print("\n Búsqueda de valores nulos")
print(df_articles.isnull().sum()) #primero evalua si hay nulos y luego los suma
print("\n Formato de los datos")
print(df_articles.dtypes) #si es un atributo no lleva () luego de la orden
Muestra de datos
article_id article_name unit_price
0 20015 Smartphone 525.00
1 20016 Full Pc 2127.81
2 20017 Monitor 230.00
3 20018 Tablet 130.00
4 20019 Desk 130.10
Formato del dataframe
(31, 3)
Búsqueda de valores nulos
article_id 0
article_name 0
unit_price 0
dtype: int64
Formato de los datos
article_id int64
article_name object
unit_price object
dtype: object
# Exploración del df de vendedores
print("Muestra de datos")
print(df_sellers.head())
print("\nFormato del dataframe")
print(df_sellers.shape)
print("\n Búsqueda de valores nulos")
print(df_sellers.isnull().sum()) #primero evalua si hay nulos y luego los suma
print("\n Formato de los datos")
print(df_sellers.dtypes) #si es un atributo no lleva () luego de la orden
Muestra de datos
seller_name
seller_id
1 Aveline Swanwick
2 Jase Doy
3 Oliviero Charkham
4 Cornie Wynrehame
5 Ewell Peres
Formato del dataframe
(15, 1)
Búsqueda de valores nulos
seller_name 0
dtype: int64
Formato de los datos
seller_name object
dtype: object
# Exploración del df de órdenes
print("Muestra de datos")
print(df_orders.head())
print("\nFormato del dataframe")
print(df_orders.shape)
print("\n Búsqueda de valores nulos")
print(df_orders.isnull().sum()) #primero evalua si hay nulos y luego los suma
print("\n Formato de los datos")
print(df_orders.dtypes) #si es un atributo no lleva () luego de la orden
Muestra de datos
order_id week article_id quantity seller_id country_name
0 15024 1 20039 10 10 Peru
1 15025 1 20029 15 5 Peru
2 15026 1 20024 5 14 Bolivia
3 15027 1 20018 9 14 Brazil
4 15028 1 20035 6 15 Mexico
Formato del dataframe
(1000, 6)
Búsqueda de valores nulos
order_id 0
week 0
article_id 0
quantity 0
seller_id 0
country_name 0
dtype: int64
Formato de los datos
order_id int64
week int64
article_id int64
quantity int64
seller_id int64
country_name object
dtype: object
df_articles ["unit_price"] = df_articles["unit_price"].astype(float)
print(df_articles.dtypes)
article_id int64
article_name object
unit_price float64
dtype: object
#CREO UNA COPIA DEL df_orders por si se rompe
my_df = df_orders.copy()
#realizo mi pendiente en el comentario, cambio el índice del df_articles
#saca la primera columna que enumeraba del 0 al 31
df_articles.set_index("article_id", inplace= True) #inplace me aplica el cambio directo en el df, es otra forma de nombrar los índices análoga al index_col del df_sellers
print(df_articles)
#print(df_articles.loc[20017]["article_name"]) #ver en video 11.11hs
article_name unit_price
article_id
20015 Smartphone 525.00
20016 Full Pc 2127.81
20017 Monitor 230.00
20018 Tablet 130.00
20019 Desk 130.10
20020 Chair 335.64
20021 Modem 67.50
20022 Range Extender 20.45
20023 Notebook 1000.00
20024 Netbook 145.00
20025 HDD 54.62
20026 SDD 22.00
20027 Ram Memory 35.95
20028 Motherboard 138.38
20029 Mouse 30.30
20030 Fan Cooler 4.25
20031 Webcam 20.07
20032 Keyboard 22.60
20033 Headphones 23.30
20034 Scanner 185.00
20035 Case 37.90
20036 Video Card 131.50
20037 CPU 139.62
20038 Power Supply 43.95
20039 Water Cooling 67.50
20040 Heatsink 10.00
20041 Usb Cable 2.95
20042 Sata Cable 2.14
20043 Pci Express Port 10.12
20044 Wi-Fi Card 59.61
20045 Mesh Wi-Fi X 2 32.50
print(my_df.head())
order_id week article_id quantity seller_id country_name
0 15024 1 20039 10 10 Peru
1 15025 1 20029 15 5 Peru
2 15026 1 20024 5 14 Bolivia
3 15027 1 20018 9 14 Brazil
4 15028 1 20035 6 15 Mexico
#agrego las columnas que me faltan
my_df = my_df.assign(article_name = my_df["article_id"]) #assign crea una columna con el nombre (article_name) y le pone el contenido que le asigno
my_df = my_df.assign(total_amount = my_df["article_id"])
my_df = my_df.assign(seller_name = my_df["seller_id"])
#ESTE BLOQUE NO SE PUEDE CORRER MÁS DE UNA VEZ PORQUE NO VA A PODER OPERAR SOBRE LOS CAMBIOS REALIZADOS.
#reemplazar los datos en las nuevas columnas
#print(len(my_df.index))
for i in range(len(my_df.index)):
#columna article_name
#cargo el nombre del artículo en una variable
article = df_articles.loc[my_df.loc[i]['article_name']]['article_name']
#se lo asigno a la columna y registro que corresponde
my_df.loc[i, "article_name"] = article
#columna total_amount
my_df.loc[i, "total_amount"] = my_df.loc[i, "quantity"] * df_articles.loc[my_df.loc[i]['total_amount']]['unit_price']
#columna de seller_name
my_df.loc[i,'seller_name'] = df_sellers.loc[my_df.loc[i]['seller_name']]['seller_name']
print(my_df.head())
order_id week article_id quantity seller_id country_name \
0 15024 1 20039 10 10 Peru
1 15025 1 20029 15 5 Peru
2 15026 1 20024 5 14 Bolivia
3 15027 1 20018 9 14 Brazil
4 15028 1 20035 6 15 Mexico
article_name total_amount seller_name
0 Water Cooling 675.0 Cirilo Grandham
1 Mouse 454.5 Ewell Peres
2 Netbook 725.0 Janel O'Curran
3 Tablet 1170.0 Janel O'Curran
4 Case 227.4 Daisie Slograve
#elimino las columnas que no necesito
my_df.drop(['order_id','article_id','seller_id'], axis='columns', inplace=True)
#inplace= True es para que me lo haga en este df y no modifique el df original
print(my_df)
week quantity country_name article_name total_amount seller_name
0 1 10 Peru Water Cooling 675.0 Cirilo Grandham
1 1 15 Peru Mouse 454.5 Ewell Peres
2 1 5 Bolivia Netbook 725.0 Janel O'Curran
3 1 9 Brazil Tablet 1170.0 Janel O'Curran
4 1 6 Mexico Case 227.4 Daisie Slograve
.. ... ... ... ... ... ...
995 4 1 Brazil Modem 67.5 Kati Innot
996 4 15 Brazil Heatsink 150.0 Daisie Slograve
997 4 2 Colombia Heatsink 20.0 Vasily Danilyuk
998 4 14 Brazil Tablet 1820.0 Vasily Danilyuk
999 4 12 Brazil SDD 264.0 Onida Cosely
[1000 rows x 6 columns]
# RESOLUCIÓN ANALÍTICA
#creo un nuevo df para agrupar por articles
my_df2 = my_df.groupby("article_name").sum() #el criterio de agrupamiento se convierte en el índice
por_cant = my_df2.sort_values("quantity", ascending = False)
print(por_cant["quantity"].head(1))
article_name
HDD 413
Name: quantity, dtype: int64
# RESOLUCIÓN GRÁFICA
plt.figure(figsize=(8,5))
font = {'family': 'serif',
'color': 'darkred',
'weight': 'normal',
'size': 16,
}
sns.displot(my_df, x = "article_name", color="darkcyan") #gráfica de distribución
plt.ylabel("Cantidad de artículos vendidos")
plt.xlabel("Artículo")
plt.xticks(rotation = 90)
plt.title("Venta de artículos por unidades", fontdict= font, loc= "left")
plt.show()
# RESOLUCIÓN ANALÍTICA
my_df3= (my_df.groupby("article_name").sum().sort_values("total_amount", ascending= False)).head(10)
print(my_df3)
print (my_df3["total_amount"].head(1))
week quantity total_amount
article_name
Full Pc 70 253 538335.93
Notebook 69 251 251000.00
Smartphone 74 290 152250.00
Chair 56 207 69477.48
Tablet 90 374 48620.00
Monitor 53 208 47840.00
Netbook 95 320 46400.00
Scanner 54 221 40885.00
Motherboard 79 291 40268.58
CPU 66 266 37138.92
article_name
Full Pc 538335.93
Name: total_amount, dtype: float64
# RESOLUCIÓN GRÁFICA
fig = plt.figure(figsize=(8, 5) )
font2 = {'family': 'serif',
'color': 'olive',
'weight': 'normal',
'size': 16,
}
#sns.scatterplot(data=my_df3, x="quantity", y= my_df3.index, color="darkred", size= round(my_df3["total_amount"], 2), legend="full", alpha = 0.7, sizes=(20, 1500))
plt.barh(my_df3.index, my_df3["total_amount"], color="darkcyan")
plt.title("Artículo que más ingresos proporcionó\n", loc="left", fontdict= font)
plt.xlabel("Monto total de ingresos (en u$d)")
plt.ylabel("Productos")
#plt.yticks(rotation=60)
plt.show()
# RESOLUCIÓN ANALÍTICA
df4 = (my_df.groupby("seller_name").sum()).sort_values("total_amount", ascending=False)
print(df4[["quantity"]+["total_amount"]])
quantity total_amount
seller_name
Janel O'Curran 703 192832.47
Brockie Patience 441 142709.88
Oliviero Charkham 555 141329.76
Vasily Danilyuk 521 129157.55
Daisie Slograve 554 120520.11
Aveline Swanwick 629 118874.33
Arnold Kilkenny 583 94552.04
Kati Innot 512 83704.62
Jase Doy 582 80628.31
Ewell Peres 496 78144.32
Onida Cosely 535 77373.37
Milly Christoffe 442 61733.69
Tobin Roselli 519 56984.42
Cornie Wynrehame 523 52253.57
Cirilo Grandham 470 45009.40
# RESOLUCIÓN GRÁFICA
plt.bar(df4.index, df4["total_amount"], color="darkcyan")
plt.xticks(rotation=90)
plt.xlabel("Vendedor/a")
plt.ylabel("Monto total")
plt.title("Ventas por vendedor(en u$d)", fontdict=font, loc="left")
plt.show()
# RESOLUCIÓN ANALÍTICA
df5 =(my_df.groupby("week").sum()).sort_values("total_amount", ascending=False)
print(df5)
quantity total_amount
week
1 2449 507458.81
2 2444 415364.44
3 2114 329140.03
4 1058 223844.56
# RESOLUCIÓN GRÁFICA
fig = plt.figure()
c=["black", "dimgrey", "darkgrey", "lightgrey"]
plt.bar(df5.index, df5["total_amount"], color= c, tick_label=[1,2,3,4] )
plt.xlabel("Semana")
plt.ylabel("Monto total vendido (en u$d)")
plt.title("Monto total vendido por semana\n", fontdict=font, loc="left")
plt.show()
# RESOLUCIÓN
df_pais_fact = ((my_df.groupby("country_name")).sum().sort_values("total_amount", ascending=False)).head(5)
df_pais_art = ((my_df.groupby("country_name")).sum().sort_values("quantity", ascending=False)).head(5)
print(df_pais_fact["total_amount"], df_pais_art["quantity"])
country_name
Brazil 441271.85
Argentina 205832.78
Colombia 177514.29
Peru 161421.12
Mexico 138619.99
Name: total_amount, dtype: float64 country_name
Brazil 2515
Peru 1027
Argentina 947
Colombia 881
Mexico 846
Name: quantity, dtype: int64
#RESOLUCIÓN GRÁFICA
font3 = {'family': 'serif',
'color': 'darkred',
'weight': 'normal',
'size': 15,
}
c = ["gold", "olivedrab", "lightcoral", "teal", "purple"]
plt.figure(figsize=(20, 15))
#TRABAJO CON LA GRÁFICA DE FACTURACIÓN
plt.subplot(2, 2, 1)
plt.bar(df_pais_fact.index, df_pais_fact["total_amount"], color=c)
plt.ylabel('monto total en US$', fontdict=font3)
plt.yticks(rotation=45)
plt.title("Ventas: top 5 países", loc="left", fontdict=font3)
plt.subplot(2, 2, 2)
plt.pie(x= df_pais_fact["quantity"], labels=df_pais_fact.index, autopct= "%1.2f%%", explode = (0.1, 0,0,0,0), colors=c)
plt.title("Top five países, monto total.\n Distribución porcentual.", loc="right", fontdict=font3)
#TRABAJO CON LA GRÁFICA DE CANTIDAD DE PRODUCTOS
plt.subplot(2, 2, 3)
plt.bar(df_pais_art.index, df_pais_art["quantity"], color= c)
plt.ylabel('Artículos totales', fontdict=font3)
plt.yticks(rotation=45)
plt.title("Cantidad de productos: top 5 países", loc="left", fontdict=font3)
plt.subplot(2, 2, 4)
plt.pie(x= df_pais_art["quantity"], labels=df_pais_art.index, autopct= "%1.2f%%", explode = (0.1, 0,0,0,0), colors=c)
plt.title("Top five países, cantidad de productos.\n Distribución porcentual.\n", loc="right", fontdict=font3)
# RESOLUCIÓN
dff6 = my_df[((my_df['article_name'] == 'Notebook')| (my_df['article_name']=='Smartphone')) & ((my_df['country_name'] == 'Argentina') | (my_df['country_name']=='Brazil')| (my_df['country_name']=='Peru'))]
df6 = dff6.drop(["week", "total_amount", "seller_name"], axis="columns")
#borro del df las columnas que no voy a utilizar
df6 = dff6.drop(["week", "total_amount", "seller_name"], axis="columns")
sns.barplot(x= df6["country_name"], y = df6["quantity"], hue= "article_name", data=df6)
plt.xlabel("")
plt.ylabel("")
plt.title("Tendencia de venta de unidades de\n Notebooks y Smartphones en\n Argentina, Brasil y Perú.", loc= "right", fontdict=font)
# RESOLUCIÓN ANALÍTICA
my_df77= (my_df.groupby(["article_name"]).sum().sort_values("quantity", ascending= False).head(20))
my_df7=my_df77.drop("week", axis="columns")
print (my_df7)
quantity total_amount
article_name
HDD 413 22558.06
Tablet 374 48620.00
SDD 372 8184.00
Mouse 322 9756.60
Netbook 320 46400.00
Ram Memory 293 10533.35
Motherboard 291 40268.58
Pci Express Port 291 2944.92
Smartphone 290 152250.00
Range Extender 281 5746.45
Heatsink 280 2800.00
Usb Cable 273 805.35
Power Supply 269 11822.55
CPU 266 37138.92
Sata Cable 264 564.96
Full Pc 253 538335.93
Water Cooling 252 17010.00
Notebook 251 251000.00
Modem 244 16470.00
Headphones 239 5568.70
# RESOLUCIÓN GRÁFICA
fig = plt.figure(figsize=(8, 8) )
font2 = {'family': 'serif',
'color': 'olive',
'weight': 'normal',
'size': 16,
}
#sns.scatterplot(x=my_df7["quantity"], y= my_df7.index, color="tab:purple", size= round(my_df3["total_amount"], 2), legend=True, alpha = 0.9, sizes=(2000, 35000))
sns.scatterplot(my_df7["quantity"], my_df7.index, color="tab:purple", size= round(my_df7["total_amount"], 2), alpha=0.8, sizes=(20, 3000))
plt.title("Artículos que más ingresos proporcionó\n", loc="left", fontdict= font2)
plt.show()
/shared-libs/python3.9/py/lib/python3.9/site-packages/seaborn/_decorators.py:36: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.
warnings.warn(