# imports
import numpy as np
import pandas as pd
import sqlite3 as sql3
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')
sql_query = pd.read_sql_query('SELECT * FROM articles', conn)
df_articles = pd.DataFrame(sql_query, columns=['article_id','article_name','unit_price'])
print(df_articles)
# VENDEDORES
df_sellers = pd.read_excel('/work/data/sellers.xlsx', index_col=0)
print(df_sellers)
# ÓRDENES
df_orders = pd.read_csv('/work/data/orders.csv')
print(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('\nBúsqueda de valores nulos')
print(df_articles.isnull().sum())
print('\nFormato de los datos')
print(df_articles.dtypes)
# Exploración del df de vendedores
print('Muestra de datos')
print(df_sellers.head())
print('\nFormato del dataframe')
print(df_sellers.shape)
print('\nBúsqueda de valores nulos')
print(df_sellers.isnull().sum())
print('\nFormato de los datos')
print(df_sellers.dtypes)
# Exploración del df de órdenes
print('Muestra de datos')
print(df_orders.head())
print('\nFormato del dataframe')
print(df_orders.shape)
print('\nBúsqueda de valores nulos')
print(df_orders.isnull().sum())
print('\nFormato de los datos')
print(df_orders.dtypes)
df_articles['unit_price'] = df_articles['unit_price'].astype(float)
print(df_articles.dtypes)
# Creo una copia del df_orders
my_df = df_orders.copy()
# Cambio el índice del df_articles
df_articles.set_index('article_id', inplace=True)
print(df_articles.head())
# agrego las columnas que me faltan
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(my_df.head())
# reemplazar los datos ne las nuevas columnas
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]['article_id']]['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())
# elimino las columnas que no necesito
my_df.drop(['order_id', 'article_id','seller_id'], axis='columns', inplace=True)
print(my_df.head())
# RESOLUCIÓN ANALÍTICA
my_df2 = my_df.groupby('article_name').sum()
por_cant = my_df2.sort_values('quantity', ascending=False)
print(por_cant['quantity'].head(1))
# RESOLUCIÓN GRÁFICA
sns.displot(my_df, x='article_name')
plt.xticks(rotation=90, fontsize=8)
plt.show()
# RESOLUCIÓN ANALÍTICA
my_df3 = (my_df.groupby('article_name').sum()).sort_values('total_amount', ascending=False).head(5)
print(my_df3['total_amount'])
# RESOLUCIÓN GRÁFICA
plt.pie(x=my_df3['total_amount'],labels=my_df3.index)
plt.show()
# RESOLUCIÓN ANALÍTICA
df4 = (my_df.groupby('seller_name').sum()).sort_values('total_amount', ascending=False)
print(df4[['quantity']+['total_amount']])
# RESOLUCIÓN GRÁFICA
plt.bar(df4.index, df4['total_amount'])
plt.xticks(rotation=60)
plt.show()
# RESOLUCIÓN ANALÍTICA
df5=(my_df.groupby('week').sum()).sort_values('total_amount',ascending=False)
print(df5)
# RESOLUCIÓN GRÁFICA
plt.bar(df5.index,df5['total_amount'])
plt.show()
df6=my_df[((my_df['country_name']=='Argentina') | (my_df['country_name']=='Brazil') | (my_df['country_name']=='Peru') |(my_df['country_name']=='Colombia') ) &
((my_df['article_name']=='Full Pc')|(my_df['article_name']=='Notebook')|(my_df['article_name']=='Tablet')
|(my_df['article_name']=='Smartphone')) ]
df6 = df6.groupby(["article_name","country_name"]).sum().sort_values('quantity',ascending=False)
print(df6[['quantity']])
df6.reset_index('article_name', inplace=True)
sns.barplot(df6.index.get_level_values(0), 'quantity', data =df6, hue='article_name')
rows = ['%d year' % x for x in (100, 50, 20, 10, 5)]
values = np.arange(0, 2500, 500)
value_increment = 1000
plt.title('Dispositivos', size=14, fontweight='bold')
plt.ylabel('Unidades Vendidas',fontstyle='italic',fontsize=14, fontweight='bold')
plt.xlabel('País',fontstyle='oblique',fontsize=14, fontweight='heavy')
plt.show()
# RESOLUCIÓN
df7 = (my_df.groupby(['seller_name','week']).sum()).sort_values('quantity', ascending=False).head(15)
print(df7[['quantity']])
sns.displot(df7, x='seller_name')
plt.xticks(rotation=90, fontsize=8)
plt.ylabel('Semanas',fontstyle='italic',fontsize=14, fontweight='bold')
plt.xlabel('Vendedores',fontstyle='oblique',fontsize=14, fontweight='heavy')
plt.show()
df8 = (my_df.groupby('country_name').sum()).sort_values('total_amount', ascending=True).head(5)
print(df8[['total_amount']])
df8=(my_df.groupby('country_name').sum()).sort_values('total_amount',ascending=True).head(5)
print(df8[['quantity']+['total_amount']])
# RESOLUCIÓN GRÁFICA
fig, graf5 = plt.subplots()
graf5.bar(df8.index,df8['total_amount'])
graf5.yaxis.set_tick_params(labelleft=False,labelright=True)
graf5.xaxis.set_tick_params(rotation=60)
plt.title('Paises con caidas de ventas', size=16, fontweight='bold')
plt.ylabel('Total $ Vendido',fontstyle='italic',fontsize=14, fontweight='bold')
plt.xlabel('País',fontstyle='oblique',fontsize=14, fontweight='heavy')
plt.show()
Zona Experimental
ff = my_df[((my_df['article_name'] == 'Full Pc') |(my_df['article_name'] == 'Notebook')) & ((my_df['country_name'] == 'Argentina') | (my_df['country_name']=='Brazil'))]
print(ff)
sns.barplot(x='country_name', y='quantity', hue='week', data=ff)
df40 = (my_df.groupby(['article_name','week']).sum()).sort_values('quantity', ascending=False)
print(df40)
paises=df40.index.get_level_values(0)
#df40.loc[('Brazil','Chair')]
paises
my_df6=(my_df.groupby('country_name').sum()).sort_values('total_amount',ascending=False).head(5)
print(my_df6[['quantity']+['total_amount']])
# RESOLUCIÓN GRÁFICA
fig, graf5 = plt.subplots()
graf5.bar(my_df6.index,my_df6['total_amount'])
graf5.plot(my_df6['total_amount'])
graf5.yaxis.set_tick_params(labelleft=False,labelright=True)
graf5.xaxis.set_tick_params(rotation=30)
sns.set_palette('coolwarm')
plt.title('Top Mejores 5 Países en Ventas', size=18, fontweight='bold')
plt.ylabel('Total $ Vendido',fontstyle='italic',fontsize=14, fontweight='bold')
plt.xlabel('País',fontstyle='oblique',fontsize=14, fontweight='heavy')
plt.show()
plt.pie(x=my_df3['total_amount'],labels=my_df3.index, startangle=90)
plt.legend(my_df3['total_amount'],loc='upper left')
centre_cicle = plt.Circle((0,0),0.4, fc='white')
fig=plt.gcf()
fig.gca().add_artist(centre_cicle)
plt.title('Artículos que proporcionaron mayores ingresos')
plt.show()
art2 = my_df[(my_df['article_name']== 'Notebook') | (my_df['article_name']== 'Full Pc') & ((my_df['country_name'] == 'Argentina') | (my_df['country_name']=='Brazil'))]
print(art2)
my_df60=(ff.groupby('country_name').sum()).sort_values('total_amount',ascending=False)
print(my_df60)
smarts = my_df[(my_df['article_name']== 'Smartphone')]
sa=(smarts.groupby('country_name').sum()).sort_values('total_amount',ascending=False)
print(sa)
# CONSULTA 13/7
# Graficando doble agrupamiento
ff=my_df[((my_df['country_name']=='Argentina') | (my_df['country_name']=='Brazil')) & ((my_df['article_name']=='Full Pc')|(my_df['article_name']=='Notebook')) ]
ff = ff.groupby(["article_name","country_name"]).sum().sort_values('total_amount',ascending=False)
# para facilitar la gráfica, uno de los índices que me quedaron después del agrupamiento, lo puedo convertir a columna nuevamente
ff.reset_index('article_name', inplace=True)
print(ff)
sns.barplot(ff.index.get_level_values(0), 'total_amount', data =ff, hue='article_name')
df9 = my_df.groupby(["country_name","article_name"]).sum()
prod_cant = df9.sort_values("quantity", ascending=False)
print(prod_cant)
print(prod_cant.loc[('Peru','Mouse')]['quantity'])
# GRÁFICA BARRAS APILADAS
my_df8 = my_df[(my_df['article_name'] == 'Full Pc') | (my_df['article_name'] == 'Notebook')| (my_df['article_name'] == 'Tablet')| (my_df['article_name'] == 'Smartphone')| (my_df['article_name'] == 'Chair')]
print(my_df8)
my_df8b=(my_df8.groupby(['seller_name','article_name']).sum()).sort_values('quantity',ascending=False)
print(my_df8b)
my_df8b.reset_index(inplace=True)
print(my_df8b)
s1= sns.barplot(x='seller_name',y='quantity',data=my_df8b)
s2= sns.barplot(x='seller_name',y='quantity',data=my_df8b)
plt.xticks(rotation=90)
plt.show()
vendedores = ['vendedor A', 'vendedor B', 'vendedor C', 'vendedor D']
full_pc = [120,544,254,235]
notebook = [45,55,45,221]
indice = np.arange(len(vendedores))
plt.bar(indice, full_pc, label='Full PC')
plt.bar(indice, notebook, label='Full PC')
plt.xticks(indice, vendedores)
plt.xlabel("Vendedor")
plt.show()