# A veces necesitamos instalar nuevas librerías en nuestros proyectos
!pip install openpyxl==3.0.10
Collecting openpyxl==3.0.10
Downloading openpyxl-3.0.10-py2.py3-none-any.whl (242 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 242.1/242.1 KB 37.5 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 pandas as pd
import sqlite3 as sql3
import openpyxl # para que levante bien el excel
import matplotlib.pyplot as plt
import seaborn as sns
# Levanto los datos en 3 diferentes dataframes
# Artículos
conn = sql3.connect('/work/data/articles.db')
df_articles = pd.read_sql_query('SELECT article_id, article_name, unit_price FROM articles', conn)
#df_articles = pd.DataFrame(sql_query, columns = ['article_id', 'article_name', 'unit_price'])
# Vendedores
df_sellers = pd.read_excel('/work/data/sellers.xlsx', index_col=0)
# Órdenes
df_orders = pd.read_csv('/work/data/orders.csv')
def imprimirDatos(df):
print('Muestra de datos')
print(df.head())
print('\nFormato del dataframe')
print(df.shape)
print('\nBúsqueda de valores nulos por columna')
print(df.isnull().sum())
print('\nFormato de los datos por columna')
print(df.dtypes)
# Exploración del df de artículos
imprimirDatos(df_articles)
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 por columna
article_id 0
article_name 0
unit_price 0
dtype: int64
Formato de los datos por columna
article_id int64
article_name object
unit_price object
dtype: object
# Exploración del df de vendedores
imprimirDatos(df_sellers)
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 por columna
seller_name 0
dtype: int64
Formato de los datos por columna
seller_name object
dtype: object
# Exploración del df de órdenes
imprimirDatos(df_orders)
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 por columna
order_id 0
week 0
article_id 0
quantity 0
seller_id 0
country_name 0
dtype: int64
Formato de los datos por columna
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
my_df = df_orders.copy()
# Cambio el índice del df de artículos
df_artic = df_articles.set_index('article_id',inplace = False)
# Agrego algunas columnas y pongo el campo que me va a servir de "ancla" para acordarme
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'])
# reemplazo los valores en el nuevo df
# 1. busco el nombre del artículo y lo asigno a una variable
# como df_articles está indexado por article_id, lo uso para ubicarme en
# el registro que busco
# SINTAXIS: df_articles.loc[indice][columna]
# [indice] va a ser el dato que obtengo de my_df.loc[i]['article_id']
# -> o sea, tomo registro a registro el article_id y lo uso para extraer
# el nombre del artículo
for i in range(len(my_df.index)): # len(my_df.index) devuelve la cantidad de registros
# Obtenemos article_name
id_articulo = my_df.loc[i]['article_id']
nombreArticulo = df_artic.loc[id_articulo]['article_name']
#se lo asigno a la columna correspondiente
my_df.loc[i,'article_name'] = nombreArticulo
# Obtenemos total_amount
precioArticulo = df_artic.loc[id_articulo]['unit_price']
my_df.loc[i, 'total_amount'] = my_df.loc[i,'quantity'] * precioArticulo
# Obtenemos seller_name
id_vendedor = my_df.loc[i]['seller_id']
nombreVendedor = df_sellers.loc[id_vendedor]['seller_name']
my_df.loc[i, 'seller_name'] = nombreVendedor
# elimino las columnas que no necesito
my_df.drop(['order_id', 'article_id', 'seller_id'], axis = 'columns', inplace=True)
my_df.round(2)
weekint64
1 - 4
quantityint64
1 - 15
0
1
10
1
1
15
2
1
5
3
1
9
4
1
6
5
1
6
6
1
13
7
1
14
8
1
7
9
1
4
# RESOLUCIÓN ANALÍTICA
df_cant_articulos = my_df.groupby('article_name').sum()
df_cant_articulos_ord = df_cant_articulos.sort_values('quantity', ascending=False)
print(df_cant_articulos_ord['quantity'].head(1) )
df_cant_articulos_ord.round(2)
article_name
HDD 413
Name: quantity, dtype: int64
weekint64
44 - 113
quantityint64
141 - 413
Webcam
68
229
Desk
60
223
Scanner
54
221
Mesh Wi-Fi X 2
64
213
Video Card
65
209
Monitor
53
208
Chair
56
207
Case
54
206
Fan Cooler
64
205
Keyboard
44
165
sns.set_palette('bright')
# RESOLUCIÓN GRÁFICA
sns.barplot(y = df_cant_articulos_ord["quantity"], x=df_cant_articulos_ord.index)
plt.xticks(rotation=90)
plt.show()
# RESOLUCIÓN ANALÍTICA
df_monto_articulo_ord = my_df.groupby('article_name').sum().sort_values('total_amount', ascending=False).head(5)
print(df_monto_articulo_ord)
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
# RESOLUCIÓN GRÁFICA
# plt.pie(x=df_monto_articulo_ord['total_amount'], labels=df_monto_articulo_ord.index)
# plt.show()
plt.barh(df_monto_articulo_ord.index, df_monto_articulo_ord['total_amount'] , height=0.7)
plt.show()
# RESOLUCIÓN ANALÍTICA
df_monto_vendedor_ord = my_df.groupby('seller_name').sum().sort_values('total_amount', ascending=False)
print(df_monto_vendedor_ord[['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(df_monto_vendedor_ord.index, df_monto_vendedor_ord['total_amount'])
plt.xticks(rotation=45, ha="right")
plt.show()
# RESOLUCIÓN ANALÍTICA
df_venta_semanal = my_df.groupby(by='week').sum().sort_values('total_amount',ascending=False)
print(df_venta_semanal['total_amount'])
week
1 507458.81
2 415364.44
3 329140.03
4 223844.56
Name: total_amount, dtype: float64
# RESOLUCIÓN GRÁFICA
plt.bar(df_venta_semanal.index,df_venta_semanal['total_amount'], width=0.8)
plt.show()
# RESOLUCIÓN
df_ventas_paises = my_df.groupby('country_name').sum().sort_values('total_amount',ascending=False).head()
df_ventas_paises['total_amount'].round(2)
# RESOLUCIÓN
# ¿Cual es la semana de mayor venta para cada pais?
# Previsualizar el DF final
# Pais1 4 monto
# Pais2 3 monto
df_pais_semana = my_df.groupby(['country_name','week']).sum()
paises = my_df.groupby('country_name').sum().index.values
#print(type(paises))
df_p_s = pd.DataFrame(columns=['Semana', 'Ventas'], index=paises)
for p in paises:
df = df_pais_semana.loc[p]
m = df.max()['total_amount']
w = df[(df['total_amount'] == m)].index[0]
#print('Pais:',p,' Semana:',w,' Total ventas:', m)
df_p_s.loc[p]= {'Semana': w, 'Ventas': m }
df_p_s['Semana'] = df_p_s['Semana'].astype(int)
#print(df_p_s)
g=sns.barplot(data=df_p_s, x=df_p_s.index ,y='Ventas', hue='Semana')
g.set_xticklabels(labels=df_p_s.index,rotation=90)
plt.show()
# RESOLUCIÓN
df_sells_semana = my_df.groupby(['week','seller_name']).sum()
df_sells_semana.reset_index(inplace=True)
sns.boxplot(x='week' ,y='total_amount', data= df_sells_semana)