# Levanto los datos en 3 diferentes dataframes
# Artículos
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'])
# Vendedores
df_sellers = pd.read_excel('/work/data/sellers.xlsx', index_col=0)
# Ordenes
df_orders = pd.read_csv('/work/data/orders.csv')
# Exploración del df de artículos
print('Muestra de datos')
print(df_articles.head()) # head() 5 Filas por defecto
print('\nFormato del dataframe')
print(df_articles.shape)
print('\nBúsqueda de valores nulls por columna')
print(df_articles.isnull().sum())
print('\nFormato de los datos por columna')
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)
Búsqueda de valores nulls 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
print('Muestra de datos')
print(df_sellers.head()) # head() 5 Filas por defecto
print('\nFormato del dataframe')
print(df_sellers.shape)
print('\nBúsqueda de valores nulls por columna')
print(df_sellers.isnull().sum())
print('\nFormato de los datos por columna')
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)
Búsqueda de valores nulls por columna
seller_name 0
dtype: int64
Formato de los datos por columna
seller_name object
dtype: object
# Exploración del df de órdenes
print('Muestra de datos')
print(df_orders.head()) # head() 5 Filas por defecto
print('\nFormato del dataframe')
print(df_orders.shape)
print('\nBúsqueda de valores nulls por columna')
print(df_orders.isnull().sum())
print('\nFormato de los datos por columna')
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)
Búsqueda de valores nulls 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
my_df = df_orders.copy() # shallow copy o copia superficial (otro Objeto alojado en la memoria)
# Cambio el índice del df de artículos
df_articles.set_index('article_id', inplace=True)
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'])
# df_articles
# print()
# my_df
for i in range(max(my_df.count())):
# print(i)
# 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 (article_name) de df_articles
# print(df_articles.loc[my_df.loc[i]['article_id']]['article_name'])
article = df_articles.loc[my_df.loc[i]['article_id']]['article_name']
# print(article)
# Asignar a cada valor id de la columna 'article_name' (my_df) el nombre del artículo
my_df.loc[i, 'article_name'] = article
# my_df
# hacemos lo mismo con total_amount
my_df.loc[i, 'total_amount'] = my_df.loc[i, 'quantity']*df_articles.loc[my_df.loc[i]['article_id']]['unit_price']
# Columna de seller name
my_df.loc[i, 'seller_name'] = df_sellers.loc[my_df.loc[i]['seller_id']]['seller_name']
# elimimo las columnas que no necesito del df
my_df.drop(['order_id', 'article_id', 'seller_id'], axis='columns', inplace=True)
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
print(my_df['article_name'].value_counts()) # cuenta valores únicos
HDD 47
SDD 45
Netbook 45
Tablet 40
Usb Cable 39
Sata Cable 38
Pci Express Port 37
Range Extender 36
Smartphone 35
Headphones 34
Heatsink 34
Power Supply 34
Mouse 34
Full Pc 34
Motherboard 33
Water Cooling 32
Video Card 31
Ram Memory 31
Notebook 30
CPU 29
Modem 29
Mesh Wi-Fi X 2 28
Desk 28
Webcam 28
Case 26
Monitor 26
Fan Cooler 25
Chair 24
Scanner 24
Wi-Fi Card 22
Keyboard 22
Name: article_name, dtype: int64
# RESOLUCIÓN GRÁFICA
sns.displot(my_df, x='article_name')
plt.xticks(rotation=90) # 'vertical'
plt.show()
# RESOLUCIÓN ANALÍTICA
df2=(my_df.groupby(by='article_name').sum()).sort_values('total_amount', ascending=False).head(5)
pd.options.display.float_format= '$ {:,.2f}'.format
print(df2['total_amount'])
# 'article_name' es el index
# print(df2) # agrupa (y suma) sólo datos numéricos
# SINTAXIS ALTERNATIVA
# pd.options.display.float_format= '$ {:,.2f}'.format
# print(my_df[['article_name'] + ['total_amount']].groupby(['article_name']).sum().sort_values('total_amount', ascending=False).head(5))
article_name
Full Pc $ 538,335.93
Notebook $ 251,000.00
Smartphone $ 152,250.00
Chair $ 69,477.48
Tablet $ 48,620.00
Name: total_amount, dtype: float64
# RESOLUCIÓN GRÁFICA
plt.pie(x=df2['total_amount'], labels=df2.index, autopct='%1.2f%%')
plt.show()
# 'article_name' es el index
# RESOLUCIÓN ANALÍTICA
df4 = (my_df.groupby(by='seller_name').sum()).sort_values('total_amount', ascending=False)
pd.options.display.float_format= '$ {:,.2f}'.format
# print(df4[['quantity'] + ['total_amount']])
print(df4[['quantity'] + ['total_amount']].head(5))
# 'seller_anme' es el index
quantity total_amount
seller_name
Janel O'Curran 703 $ 192,832.47
Brockie Patience 441 $ 142,709.88
Oliviero Charkham 555 $ 141,329.76
Vasily Danilyuk 521 $ 129,157.55
Daisie Slograve 554 $ 120,520.11
# RESOLUCIÓN GRÁFICA
plt.bar(df4.index, df4['total_amount'])
plt.xticks(rotation=60)
plt.show()
# 'seller_anme' es el index
# RESOLUCIÓN ANALÍTICA
df5 = (my_df.groupby(by='week').sum()).sort_values('total_amount', ascending=False)
pd.options.display.float_format= '$ {:,.2f}'.format
print(df5[['quantity'] + ['total_amount']])
# 'week' es el index
quantity total_amount
week
1 2449 $ 507,458.81
2 2444 $ 415,364.44
3 2114 $ 329,140.03
4 1058 $ 223,844.56
# RESOLUCIÓN GRÁFICA
plt.bar(df5.index, df5['total_amount'])
plt.show()
# 'week' es el index
# RESOLUCIÓN
# Ventas filtrado por país. Comparar 2 países
# Cuál es el producto que más se vende, en qué cantidad
# Resolución Analítica y Gráfica
# Res. Análitica
print("VENTAS TOTALES POR PAIS")
df_pais = my_df
#print(df_pais)
print(df_pais.groupby(['country_name']).agg({'total_amount':'sum'}).sort_values('total_amount', ascending=False))
df_ranking=df_pais.groupby(['country_name']).agg({'total_amount':'sum'}).sort_values('total_amount', ascending=False)
VENTAS TOTALES POR PAIS
total_amount
country_name
Brazil $ 441,271.85
Argentina $ 205,832.78
Colombia $ 177,514.29
Peru $ 161,421.12
Mexico $ 138,619.99
Venezuela $ 77,684.52
El Salvador $ 57,391.26
Guatemala $ 52,579.25
Honduras $ 36,763.56
Costa Rica $ 34,606.50
Chile $ 24,660.98
Bolivia $ 22,682.80
Uruguay $ 17,843.09
Ecuador $ 17,475.30
Paraguay $ 8,195.12
Puerto Rico $ 1,265.43
# Res. Grafica
print("VENTAS TOTALES POR PAIS")
sns.barplot(df_ranking.index, df_ranking['total_amount'],palette='icefire')
plt.xticks(rotation=90)
plt.title("VENTAS TOTALES POR PAIS")
plt.xlabel("PAIS")
plt.ylabel("VENTAS TOTALES ($)")
plt.yticks(np.arange(0,450001,25000))
plt.show()
VENTAS TOTALES POR PAIS
/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(
# Comparación Brasil-Argentina (Top 2), en unidades ("quantity") y ventas ("total_amount")
# Res. Analítica
print("COMPARACION BRA/ARG - TOP 2")
df_pais2 = (my_df.groupby(by= 'country_name').sum()).sort_values('total_amount', ascending=False)
pd.options.display.float_format= '$ {:,.2f}'.format
# print(df4[['quantity'] + ['total_amount']])
print(df_pais2[['quantity'] + ['total_amount']].head(2))
df_pais3=df_pais2[['quantity'] + ['total_amount']].head(2)
COMPARACION BRA/ARG - TOP 2
quantity total_amount
country_name
Brazil 2515 $ 441,271.85
Argentina 947 $ 205,832.78
# Res. Grafica
print("COMPARACION BRA/ARG - TOP 2 - VENTAS")
sns.barplot(df_pais3.index, df_pais3['total_amount'],color='C3')
plt.xticks(rotation=90)
plt.title("COMPARACION BRA/ARG - TOP 2 - VENTA")
plt.xlabel("PAIS")
plt.ylabel("VENTAS TOTALES ($)")
plt.yticks(np.arange(0,450001,25000))
plt.show()
print("COMPARACION BRA/ARG - TOP 2 - UNIDADES")
sns.barplot(df_pais3.index, df_pais3['quantity'],color='C5')
plt.xticks(rotation=90)
plt.title("COMPARACION BRA/ARG - TOP 2 - UNIDADES")
plt.xlabel("PAIS")
plt.ylabel("UNIDADES VENDIDAS")
plt.yticks(np.arange(0,2501,250))
plt.show()
COMPARACION BRA/ARG - TOP 2 - VENTAS
/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(
COMPARACION BRA/ARG - TOP 2 - UNIDADES
/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(
#Ranking de ventas por articulos
print("RANKING DE VENTAS POR ARTICULO (CANTIDADES TOTALES)")
df_articulo2 = my_df
#print(df_articulo)
print(df_articulo2.groupby(['article_name']).agg({'quantity':'count'}).sort_values('quantity', ascending=False))
top5= (df_articulo2.groupby(['article_name']).agg({'quantity':'count'}).sort_values('quantity', ascending=False).head())
RANKING DE VENTAS POR ARTICULO (CANTIDADES TOTALES)
quantity
article_name
HDD 47
Netbook 45
SDD 45
Tablet 40
Usb Cable 39
Sata Cable 38
Pci Express Port 37
Range Extender 36
Smartphone 35
Full Pc 34
Headphones 34
Heatsink 34
Mouse 34
Power Supply 34
Motherboard 33
Water Cooling 32
Video Card 31
Ram Memory 31
Notebook 30
CPU 29
Modem 29
Mesh Wi-Fi X 2 28
Desk 28
Webcam 28
Case 26
Monitor 26
Fan Cooler 25
Scanner 24
Chair 24
Keyboard 22
Wi-Fi Card 22
# RESOLUCIÓN
# Evolución de Ventas por producto.
# Tomar 2 países y 'week' como variable categórica
# Resolución Analítica y Gráfica
# Res. Analitica (Ventas semanales en Brasil)
print("VENTAS TOTALES POR SEMANA EN BRASIL")
df_brasil = my_df.loc[(my_df['country_name'] == 'Brazil')]
print(df_brasil.groupby(['week']).agg({'total_amount':'sum'}).sort_values('total_amount', ascending=False))
df_brasil2=df_brasil.groupby(['week']).agg({'total_amount':'sum'}).sort_values('week', ascending=True)
print("UNIDADES VENDIDAS POR SEMANA EN BRASIL")
df_brasil = my_df.loc[(my_df['country_name'] == 'Brazil')]
print(df_brasil.groupby(['week']).agg({'quantity':'count'}).sort_values('week', ascending=True))
df_brasil2=df_brasil.groupby(['week']).agg({'quantity':'count'}).sort_values('week', ascending=True)
VENTAS TOTALES POR SEMANA EN BRASIL
total_amount
week
1 $ 165,289.90
2 $ 106,803.85
4 $ 89,836.60
3 $ 79,341.50
UNIDADES VENDIDAS POR SEMANA EN BRASIL
quantity
week
1 94
2 89
3 83
4 49
# Res. Grafica (Ventas semanales en Brasil)
f_brasil = my_df.loc[(my_df['country_name'] == 'Brazil')]
#print(df_brasil.groupby(['week']).agg({'total_amount':'sum'}).sort_values('total_amount', ascending=False))
df_brasil2=df_brasil.groupby(['week']).agg({'total_amount':'sum'}).sort_values('week', ascending=True)
plt.plot(df_brasil2,color='red')
plt.title("VENTAS TOTALES POR SEMANA EN BRASIL")
plt.xlabel("SEMANA")
plt.ylabel("VENTAS TOTALES")
plt.yticks(np.arange(70000,170000,5000))
plt.xticks(np.arange(1,5,1))
plt.grid()
plt.show()
df_brasil = my_df.loc[(my_df['country_name'] == 'Brazil')]
#print(df_brasil.groupby(['week']).agg({'quantity':'count'}).sort_values('week', ascending=True))
df_brasil2=df_brasil.groupby(['week']).agg({'quantity':'count'}).sort_values('week', ascending=True)
plt.plot(df_brasil2,color='pink')
plt.title("UNIDADES VENDIDAS POR SEMANA EN BRASIL")
plt.xlabel("SEMANA")
plt.ylabel("UNIDADES")
plt.yticks(np.arange(45,100,5))
plt.xticks(np.arange(1,5,1))
plt.grid()
plt.show()
# Res. Analitica (Ventas semanales en Argentina)
print("VENTAS TOTALES POR SEMANA EN ARGENTINA")
df_argentina = my_df.loc[my_df['country_name'] == 'Argentina']
print(df_argentina.groupby(['week']).agg({'total_amount':'sum'}).sort_values('week', ascending=True))
df_argentina2=df_argentina.groupby(['week']).agg({'total_amount':'sum'}).sort_values('week', ascending=True)
print("UNIDADES VENDIDAS POR SEMANA EN ARGENTINA")
df_argentina = my_df.loc[my_df['country_name'] == 'Argentina']
print(df_argentina.groupby(['week']).agg({'quantity':'count'}).sort_values('week', ascending=True))
df_argentina2=df_argentina.groupby(['week']).agg({'quantity':'count'}).sort_values('week', ascending=True)
VENTAS TOTALES POR SEMANA EN ARGENTINA
total_amount
week
1 $ 63,760.48
2 $ 96,789.13
3 $ 26,601.97
4 $ 18,681.20
UNIDADES VENDIDAS POR SEMANA EN ARGENTINA
quantity
week
1 32
2 48
3 19
4 14
# Res. Grafica (Ventas semanales en Argentina)
df_argentina = my_df.loc[my_df['country_name'] == 'Argentina']
#print(df_argentina.groupby(['week']).agg({'total_amount':'sum'}).sort_values('week', ascending=True))
df_argentina2=df_argentina.groupby(['week']).agg({'total_amount':'sum'}).sort_values('week', ascending=True)
plt.plot(df_argentina2,color='purple')
plt.title("VENTAS TOTALES POR SEMANA EN ARGENTINA")
plt.xlabel("SEMANA")
plt.ylabel("VENTAS TOTALES")
plt.yticks(np.arange(18000,98000,5000))
plt.xticks(np.arange(1,5,1))
plt.grid()
plt.show()
df_argentina = my_df.loc[my_df['country_name'] == 'Argentina']
#print(df_argentina.groupby(['week']).agg({'quantity':'count'}).sort_values('week', ascending=True))
df_argentina2=df_argentina.groupby(['week']).agg({'quantity':'count'}).sort_values('week', ascending=True)
plt.plot(df_argentina2,color='blue')
plt.title("UNIDADES VENDIDAS POR SEMANA EN ARGENTINAA")
plt.xlabel("SEMANA")
plt.ylabel("UNIDADES")
plt.yticks(np.arange(10,50,5))
plt.xticks(np.arange(1,5,1))
plt.grid()
plt.show()
# RESOLUCIÓN
# Mejor vendedor/producto. Mostrar importe/cantidad. Comparar 2 países (variable categórica)
# Resolución Analítica y Gráfica
#Vendedor/Producto
print("ARTICULO/CANTIDAD VENDIDA POR VENDEDOR")
df_sample4 = my_df.set_index(['seller_name']).sort_index(ascending=[True])
#print(df_sample)
pd.options.display.float_format= '$ {:,.2f}'.format
#df = sns.load_dataset('df_sample')
df_sample4.groupby(['seller_name','article_name'])['quantity'].count().to_frame().sort_values('quantity', ascending=False)
print(df_sample4.groupby(['seller_name','article_name'])['quantity'].count().to_frame().sort_values('quantity', ascending=False).head(15))
ARTICULO/CANTIDAD VENDIDA POR VENDEDOR
quantity
seller_name article_name
Tobin Roselli Power Supply 9
Aveline Swanwick Netbook 7
Daisie Slograve Sata Cable 7
Oliviero Charkham Headphones 7
Jase Doy Pci Express Port 6
Cornie Wynrehame HDD 6
Daisie Slograve Monitor 6
Janel O'Curran Full Pc 6
HDD 6
Jase Doy HDD 6
Arnold Kilkenny CPU 6
Janel O'Curran Range Extender 6
Vasily Danilyuk HDD 6
Onida Cosely Water Cooling 6
Pci Express Port 5
#Grafico Importe - Cantidad Brasil
df_brazil = my_df[my_df['country_name'] == 'Brazil']
df_brazil_sellers = (df_brazil.groupby(by='seller_name').sum()).sort_values('total_amount', ascending=False).index.values
fig, ax1 = plt.subplots()
sns.barplot(x='seller_name', y='total_amount', data = df_brazil, ax=ax1, palette='Accent', order = df_brazil_sellers, ci=None)
plt.xticks(rotation=90)
ax2 = ax1.twinx()
sns.lineplot(data = df_brazil, x='seller_name', y='quantity', ax=ax2, color='C11', ci=None)
plt.xticks(rotation=90)
plt.title('VENTAS ($ Y UNIDADES) POR VENDEDOR EN BRASIL')
ax1.set_xlabel("VENDEDOR")
ax1.set_ylabel("VENTAS TOTALES (barras)")
ax2.set_ylabel("UNIDADES VENDIDAS (linea)")
plt.show()
#Grafico Importe - Cantidad Argentina
df_argentina = my_df[my_df['country_name'] == 'Argentina']
df_argentina_sellers = (df_argentina.groupby(by='seller_name').sum()).sort_values('total_amount', ascending=False).index.values
fig, ax1 = plt.subplots()
sns.barplot(x='seller_name', y='total_amount', data = df_argentina, ax=ax1, palette='rainbow_r', order = df_argentina_sellers, ci=None)
plt.xticks(rotation=90)
ax2 = ax1.twinx()
sns.lineplot(data = df_argentina, x='seller_name', y='quantity', ax=ax2, color='C11', ci=None)
plt.xticks(rotation=90)
plt.title('VENTAS ($ Y UNIDADES) POR VENDEDOR EN ARGENTINA')
ax1.set_xlabel("VENDEDOR")
ax1.set_ylabel("VENTAS TOTALES (barras)")
ax2.set_ylabel("UNIDADES VENDIDAS (linea)")
plt.show()