# A veces necesitamos instalar nuevas librerías en nuestros proyectos
!pip install openpyxl==3.0.10
# imports
import numpy as np
import pandas as pd
import sqlite3 as sql3
import openpyxl
import matplotlib.pyplot as plt
import seaborn as sns
# 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'])
# 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('\nBusqueda de valores nulls por columna')
print(df_articles.isnull().sum())
print('\nFormato de los datos por columna')
print(df_articles.dtypes)
# 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('\nBusqueda de valores nulls por columna')
print(df_sellers.isnull().sum())
print('\nFormato de los datos por columna')
print(df_sellers.dtypes)
# 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('\nBusqueda de valores nulls por columna')
print(df_orders.isnull().sum())
print('\nFormato de los datos por columna')
print(df_orders.dtypes)
df_articles['unit_price'] = df_articles['unit_price'].astype(float)
print(df_articles.dtypes)
# https://pandas.pydata.org/docs/user_guide/indexing.html
# https://towardsdatascience.com/how-to-use-loc-and-iloc-for-selecting-data-in-pandas-bd09cb4c3d79
# https://stackoverflow.com/questions/28754603/indexing-pandas-data-frames-integer-rows-named-columns
my_df = df_orders.copy() # Shallow copy
# 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'])
# print(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[i]['article_id']]['article_name'])
article = df_articles.loc[my_df.loc[i]['article_id']]['article_name']
# print(article)
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']
# elimino las columnas que no necesito del df
my_df.drop(['order_id', 'article_id', 'seller_id'], axis='columns', inplace=True)
print(my_df)
# my_df.loc[:, 'quantity']
# my_df.loc[0, ['quantity','country_name']]
# my_df.loc[0:5, ['quantity','country_name']]
# my_df.iloc[:,1]
# my_df.iloc[0,[1,2]]
my_df.iloc[0:5,[1,2]]
# RESOLUCIÓN ANALÍTICA
# df7 = my_df.groupby(by='article_name').sum().sort_values('quantity', ascending=False)
# print(df7.head())
# print(df7[['quantity']].head())
# print()
# df7 = my_df.groupby(by='article_name').sum().sort_values('quantity', ascending=False).reset_index()
# print(df7.head())
# df7_2 = df7[['article_name', 'quantity']].groupby('article_name').sum('quantity').sort_values('quantity', ascending=False)
# print(df7_2.head())
# print()
# print(df7_2.head().index)
# print(df7_2.head().index[0])
# df7 = my_df.groupby(by='article_name')['quantity'].sum().sort_values(ascending=False).head()
# df7 = my_df.groupby(by='article_name')[['quantity'] + ['total_amount']].sum().sort_values('quantity',ascending=False).head()
# print(df7)
# print(df7.head().index)
# df7 = my_df.groupby(by='article_name')['quantity'].sum().sort_values(ascending=False)
# print(df7.iloc[0:5])
# df7 = my_df.groupby(by='article_name')['quantity'].sum().sort_values(ascending=False).reset_index()
# print(df7.iloc[0:5])
# df7 = my_df.groupby(by='article_name')['quantity'].sum().sort_values(ascending=False)
# df7 = my_df.groupby(by='article_name').sum().sort_values('quantity',ascending=False)
# print(df7)
# print(df7.loc['HDD':'Netbook'])
# print(df7.loc['HDD':'Netbook']['quantity'])
# df7 = my_df.groupby(by='article_name').agg({'quantity':'sum'}).sort_values('quantity', ascending=False)
# print(df7.head())
# df7 = my_df.groupby(by='article_name').agg({'quantity':'sum'}).sort_values('quantity', ascending=False).rename(columns={'quantity':'Cantidad'}).sort_values('Cantidad', ascending=False)
# print(df7.head())
# df7 = my_df.groupby(by='article_name').agg({'quantity':'sum'}).sort_values('quantity', ascending=False).reset_index().rename(columns={'quantity':'Cantidad'}).sort_values('Cantidad', ascending=False)
# print(df7.head())
# df7 = my_df.groupby(by='article_name').sum().sort_values('quantity', ascending=False).head()
df7 = my_df.groupby(by='article_name').sum().sort_values('quantity', ascending=False)
pd.options.display.float_format= '$ {:,.2f}'.format
# print(df7[['quantity']].head())
print(df7[['quantity','total_amount']].head())
# print(df7[['quantity','total_amount']])
# RESOLUCIÓN GRÁFICA
# Opción 1 - Count
# sns.countplot(my_df, x='article_name')
# Opción 2 - barplot
sns.barplot(data=df7, x=df7.index, y='quantity')
# Opción 3 - barplot
# xs = ["HDD", "Tablet", "SDD", "Mouse", "Netbook"]
# ys = [413, 374, 372, 322, 320]
# sns.barplot(x=xs, y=ys)
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'])
# print(df2)
# print()
# print(df2.index[0])
# print()
# print(df2.reset_index().iloc[0])
# print()
# for i in range(5):
# # print(df2.index[i])
# print(df2.reset_index().iloc[i])
# print()
# print()
# print(df2.reset_index())
# RESOLUCIÓN GRÁFICA
plt.pie(x=df2['total_amount'], labels=df2.index, autopct='%1.2f%%')
plt.show()
# 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']].head(5))
# RESOLUCIÓN GRÁFICA
plt.bar(df4.index, df4['total_amount'])
plt.xticks(rotation=90)
plt.show()
# 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']])
# RESOLUCIÓN GRÁFICA
plt.bar(df5.index, df5['total_amount'])
plt.show()
# 'week' es el index
# RESOLUCIÓN ANALITICA
my_df5 = (my_df.groupby(by='country_name').sum()).sort_values('total_amount',ascending=False).head(7)
print(my_df5['total_amount'])
# RESOLUCIÓN GRAFICA
sns.barplot(y=my_df5['total_amount'], x=my_df5.index, palette='flare')
plt.suptitle('TOP 10 Paises Mayores Compras Totales',fontsize='x-large')
for pos in ['right', 'top', 'bottom', 'left']:
plt.gca().spines[pos].set_visible(False)
ingresos = my_df5['total_amount'].values
for i, ingreso in enumerate(ingresos):
v = '$ ' + str(int(ingreso))
plt.text(s=v, x=i, y=my_df5['total_amount'][i] + 15000, ha='center')
plt.xlabel('')
plt.yticks([])
plt.ylabel(ylabel='')
plt.show()
# RESOLUCIÓN ANÁLITICA
# Obtener Monto total desglosado por Pais
df_pais_articulo = my_df.groupby(['country_name', 'article_name']).sum()
# Obtener la lista de paises
paises = my_df.groupby('country_name').sum().index.values
# Seteo la estructura del DF
my_df6 = pd.DataFrame(columns=['ARTICULO', 'MONTO'], index=paises)
# Calcular los articulos mas vendidos por pais y guardarlas en df
for p in paises:
df = df_pais_articulo.loc[p]
v = df.max()['total_amount']
a = df[(df['total_amount'] == v)].index[0]
my_df6.loc[p] = {'ARTICULO': a, 'MONTO': v}
my_df6 = my_df6.sort_values(['ARTICULO', 'MONTO'])
my_df6.reset_index(inplace=True, drop=False)
my_df6.columns = ['PAIS','ARTICULO', 'MONTO']
print(my_df6)
# RESOLUCIÓN GRÁFICA
c = sns.color_palette('rocket', n_colors=my_df6.nunique(0)[1])
df_pivot = pd.pivot_table(my_df6, index='PAIS', columns='ARTICULO', values='MONTO', aggfunc='sum')
df_pivot = df_pivot.sort_values(['CPU','Full Pc', 'Monitor', 'Notebook','Smartphone'], ascending=False)
df_pivot.plot.barh(stacked=True, color=c, width=0.8)
plt.suptitle(t='PRODUCTO QUE MAS SE VENDE EN CADA PAIS Y SU MONTO TOTAL', y=1.4, fontsize='x-large')
for pos in ['right', 'top', 'bottom', 'left']:
plt.gca().spines[pos].set_visible(False)
ingresos = my_df6.values
for ingreso in ingresos:
v = '$ ' + str(int(ingreso[2]))
i = df_pivot.index.values
plt.text(s=v, x=ingreso[2] + 1000, y=np.where(i==ingreso[0])[0][0], va='center')
plt.xlabel('')
plt.xticks([])
plt.ylabel(ylabel='')
plt.show()
# RESOLUCIÓN ANÁLITICA
#Filtro del País que quiero analizar, Brasil
filter_brasil=my_df['country_name']=='Brazil'
brasil_df = my_df[filter_brasil]
#Busco los articulos más vendidos correspondientes al país en cuestión
brasil_agrupado_df=brasil_df.groupby("article_name").sum().sort_values('total_amount',ascending=False).drop(['week'], axis=1).head(10)
print (brasil_agrupado_df)
# RESOLUCIÓN GRÁFICA
colors = sns.color_palette('Set3')[0:9]
plt.pie(brasil_agrupado_df['total_amount'], labels = brasil_agrupado_df.index, colors = colors, autopct='%.0f%%')
plt.title('Desglose de Ventas Totales en el Brasil')
plt.show()
df6 = my_df[my_df['country_name'] == 'Brazil']
#A partir del anterior, ordenar vendedores por total de ventas
vendedores_pais = df6.groupby('seller_name').sum().sort_values('total_amount', ascending=False)
vendedores_pais.head()
plt.bar(vendedores_pais.index,vendedores_pais['total_amount'],
color = ['green' if x in vendedores_pais.index[0:5] else 'blue' for x in vendedores_pais.index]) #Color verde para los mejores 5
plt.xticks(rotation = 90)
plt.title("Desempeño vendedores del país que más compra")
plt.xlabel("Vendedores")
plt.ylabel("Total de Ventas")
plt.show()
df_brazil = my_df[my_df['country_name'] == 'Brazil']
print(df_brazil[['seller_name','total_amount', 'quantity']].groupby('seller_name').sum().sort_values('total_amount', ascending=False))
print()
df_brazil_bars = df_brazil[['seller_name','total_amount']].groupby('seller_name').sum('total_amount').sort_values('total_amount', ascending=False)
print(df_brazil_bars)
print()
df_brazil_line = df_brazil[['seller_name','quantity']].groupby('seller_name').sum('quantity').sort_values('quantity', ascending=False).reset_index()
print(df_brazil_line)
fig, ax1 = plt.subplots()
# ax1: axes1
# sns.barplot(data = df_brazil_bars, x='seller_name', y='total_amount', ax=ax1, color='C3')
sns.barplot(data = df_brazil_bars, x = df_brazil_bars.index, y='total_amount', ax=ax1, color='C3')
# ax: axes
plt.xticks(rotation=90)
ax2 = ax1.twinx()
# ax2: axes2 = ax1.twinx()
sns.lineplot(data = df_brazil_line, x='seller_name', y='quantity', ax=ax2, color='C11')
plt.xticks(rotation=90)
plt.title('Top sellers in Brazil')
ax1.set_xlabel("Seller Name")
ax1.set_ylabel("Income ($)")
ax2.set_ylabel("Quantity (line)")
plt.show()