# A veces necesitamos instalar nuevas librerías en nuestros proyectos
!pip install openpyxl==3.0.10
Requirement already satisfied: openpyxl==3.0.10 in /root/venv/lib/python3.9/site-packages (3.0.10)
Requirement already satisfied: et-xmlfile in /root/venv/lib/python3.9/site-packages (from openpyxl==3.0.10) (1.1.0)
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 pandas as pd
import sqlite3 as sql3
import matplotlib.pyplot as plt
import seaborn as sns
import openpyxl #para levantar excel de otros paquetes (no office)
# Levanto los datos en 3 diferentes dataframes
#Articulos
conn = sql3.connect('/work/data/articles.db')
sql_query = pd.read_sql_query('SELECT * FROM articles', conn)
df_articles = pd.DataFrame(sql_query, columns=['article_id', 'article_name', 'unit_price'])
#df_articles
#Vendedores
df_sellers = pd.read_excel('/work/data/sellers.xlsx', index_col=0)
#df_sellers
#Ordenes
df_orders = pd.read_csv('/work/data/orders.csv')
#df_orders
# Exploración del df de artículos
print('Muestra de Datos')
print(df_articles.head())
print('\nFormato del dataframe')
print(df_articles.shape)
print('\nBuscar valores nulos')
print(df_articles.isnull().sum())
print('\nFormato d elos datos del dataframe')
print(df_articles.dtypes)
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)
Buscar valores nulos
article_id 0
article_name 0
unit_price 0
dtype: int64
Formato d elos datos del dataframe
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('\nBuscar valores nulos')
print(df_sellers.isnull().sum())
print('\nFormato d elos datos del dataframe')
print(df_sellers.dtypes)
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)
Buscar valores nulos
seller_name 0
dtype: int64
Formato d elos datos del dataframe
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('\nBuscar valores nulos')
print(df_orders.isnull().sum())
print('\nFormato d elos datos del dataframe')
print(df_orders.dtypes)
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)
Buscar valores nulos
order_id 0
week 0
article_id 0
quantity 0
seller_id 0
country_name 0
dtype: int64
Formato d elos datos del dataframe
order_id int64
week int64
article_id int64
quantity int64
seller_id int64
country_name object
dtype: object
#Cambiar a float los precios unitarios
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
my_df = df_orders.copy()
#my_df
#Cambio el indice del df_articles
df_articles.set_index('article_id', inplace=True)
# Agrego 3 columnas y pongo el campo que me va a servir de "ancla" para buscar la informacion real.
my_df = my_df.assign(article_name = my_df['article_id'])
my_df = my_df.assign(total_amount = my_df['article_id'])
my_df = my_df.assign(seller_name = my_df['seller_id'])
# Reemplazamos los valores reales en el df
for i in range(len(my_df.index)): #len(my_df.index) devuelve la cantidad de filas (registros)
#Reemplazo el nombre del articulo usando el id guardado en my_df
article = df_articles.loc[my_df.loc[i]['article_id']]['article_name']
my_df.loc[i, 'article_name'] = article
#Reemplanzo el nombre del vendedor usandl el id guadado en my_df
my_df.loc[i, 'seller_name'] = df_sellers.loc[my_df.loc[i]['seller_id']]['seller_name']
#Busco el precio unitario y lo multiplico por la cantidad de unidades vendidas
my_df.loc[i, 'total_amount'] = df_articles.loc[my_df.loc[i]['article_id']]['unit_price'] * my_df.loc[i, 'quantity']
my_df.drop(['article_id', 'seller_id', 'order_id'], axis='columns', inplace=True)
print(my_df.head())
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
# RESOLUCIÓN ANALÍTICA
my_df2 = my_df.groupby('article_name').sum().sort_values('quantity', ascending=False)
#por_cantidad = my_df2.sort_values('quantity', ascending=False)
#print(por_cantidad['quantity'].head())
print(my_df2['quantity'].head(1))
article_name
HDD 413
Name: quantity, dtype: int64
# RESOLUCIÓN GRÁFICA
#my_df2.drop(['week', 'total_amount'], axis='columns', inplace=True)
#my_df2.plot(kind='bar')
#sns.barplot(x=my_df2.index, y=my_df2['quantity'], data = my_df2, order=my_df2.sort_values('quantity', ascending=False).index).set(title='Ventas por articulo')
#plt.xlabel('Cantidad vendida')
#plt.ylabel('Producto')
#plt.xticks(rotation=90)
#plt.show()
sns.set_style("white")
plt.figure(figsize=(10,5))
plt.bar(my_df2.index, my_df2['quantity'],color= 'green', alpha= 0.8)
plt.xlabel('Cantidad vendida')
plt.xticks(rotation=75)
plt.ylabel('Producto')
plt.title('Unidades vendidas por producto')
plt.savefig('/work/img/1.png', dpi=300)
plt.show()
# RESOLUCIÓN ANALÍTICA
my_df2 = my_df.groupby('article_name').sum()
mas_ingresos = my_df2.sort_values('total_amount', ascending=False).head()
print(mas_ingresos['total_amount'])
article_name
Full Pc 538335.93
Notebook 251000.00
Smartphone 152250.00
Chair 69477.48
Tablet 48620.00
Name: total_amount, dtype: float64
# RESOLUCIÓN GRÁFICA
e = (0.1,0,0,0,0)
c = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue','mediumorchid']
plt.pie(x=mas_ingresos['total_amount'], labels=mas_ingresos.index, colors=c, explode=e, autopct='%1.2f%%')
plt.title('Distribución Por Ingresos - Top 5')
plt.savefig('/work/img/2.png', dpi=300)
plt.show()
# RESOLUCIÓN ANALÍTICA
df3 = my_df.groupby('seller_name').sum().sort_values('total_amount',ascending=False)
print(df3[['quantity']+['total_amount']].head(1))
quantity total_amount
seller_name
Janel O'Curran 703 192832.47
# RESOLUCIÓN GRÁFICA
plt.bar(df3.index,df3['total_amount'], color= 'green', alpha= 0.8)
plt.xticks(rotation=75)
plt.xlabel('Vendedores')
plt.ylabel('Ventas')
plt.title('Ranking de Vendedores')
plt.savefig('/work/img/3.png', dpi=300)
plt.show()
# RESOLUCIÓN ANALÍTICA
df4 = my_df.groupby('week').sum()
print(df4)
quantity total_amount
week
1 2449 507458.81
2 2444 415364.44
3 2114 329140.03
4 1058 223844.56
# RESOLUCIÓN GRÁFICA
plt.bar(df4.index,df4['total_amount'], color= 'green', alpha= 0.8)
plt.xlabel('Semana')
plt.ylabel('Ventas Totales ($)')
plt.title('Ventas Semanales')
plt.savefig('/work/img/4.png', dpi=300)
plt.show()
# RESOLUCIÓN
df5 = my_df.groupby('country_name').sum().sort_values('total_amount',ascending=False).head(5)
print(df5[['quantity']+['total_amount']].head(5))
plt.bar(df5.index,df5['total_amount'], color= 'green', alpha= 0.8)
plt.xlabel('País')
plt.ylabel('Ventas Totales ($)')
plt.title('Ventas por país - Top 5')
plt.savefig('/work/img/5.png', dpi=300)
plt.show()
quantity total_amount
country_name
Brazil 2515 441271.85
Argentina 947 205832.78
Colombia 881 177514.29
Peru 1027 161421.12
Mexico 846 138619.99
# RESOLUCIÓN
df6 = pd.pivot_table(my_df, values='quantity', index=['article_name'], columns=['country_name'], aggfunc=np.sum ).fillna(0).round(0)
df6 = df6.reindex(columns=country_list_sorted, index=articles_list_sorted)
df6.head()
Brazilfloat64
Argentinafloat64
Full Pc
63
45
Notebook
83
43
Smartphone
79
25
Chair
112
6
Tablet
156
0
f, ax = plt.subplots(figsize=(10,9))
plt.title('Cantidad de Productos Vendidos x País')
sns.heatmap(df6, annot=True, fmt=".0f", linewidths=.5, cmap='rainbow', ax=ax)
plt.savefig('/work/img/6.png', dpi=300)
# RESOLUCIÓN
df7 = pd.pivot_table(my_df, values='quantity', index=['article_name'], columns=['seller_name'], aggfunc=np.sum ).fillna(0).round(0)
df7 = df7.reindex(columns=sellers_list_sorted, index = articles_list_sorted )
df7.head()
Janel O'Curranfloat64
Brockie Patiencefloat64
Full Pc
56
46
Notebook
17
5
Smartphone
32
21
Chair
0
20
Tablet
38
50
f, ax = plt.subplots(figsize=(10,9))
plt.title('Vendedores x Artículo')
sns.heatmap(df7, annot=True, fmt=".0f", linewidths=.5, cmap='rainbow', ax=ax)
plt.savefig('/work/img/7.png', dpi=300)