# 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("ARTÍCULO MAS VENDIDO POR UNIDADES")
print(my_df['article_name'].value_counts()) # cuenta valores únicos
ARTÍCULO MAS VENDIDO POR UNIDADES
HDD 47
SDD 45
Netbook 45
Tablet 40
Usb Cable 39
Sata Cable 38
Pci Express Port 37
Range Extender 36
Smartphone 35
Power Supply 34
Headphones 34
Mouse 34
Heatsink 34
Full Pc 34
Motherboard 33
Water Cooling 32
Video Card 31
Ram Memory 31
Notebook 30
Modem 29
CPU 29
Webcam 28
Desk 28
Mesh Wi-Fi X 2 28
Monitor 26
Case 26
Fan Cooler 25
Scanner 24
Chair 24
Wi-Fi Card 22
Keyboard 22
Name: article_name, dtype: int64
# RESOLUCIÓN GRÁFICA
sns.displot(my_df, x='article_name', palette='Accent')
plt.title("ARTÍCULO MAS VENDIDO POR UNIDADES")
plt.xticks(rotation=90) # 'vertical'
plt.show()
# RESOLUCIÓN ANALÍTICA
print("GANANCIA POR ARTÍCULO")
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))
GANANCIA POR ARTÍCULO
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.title("GANANCIA POR ARTÍCULO")
plt.pie(x=df2['total_amount'], labels=df2.index, autopct='%1.2f%%')
plt.show()
# 'article_name' es el index
# RESOLUCIÓN ANALÍTICA
print("MEJOR VENDEDOR")
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
MEJOR VENDEDOR
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
r=['skyblue', 'coral', 'lima' ]
plt.bar(df4.index, df4['total_amount'], color=r, alpha=0.55)
#plt.bar(df4.index, df4['total_amount'])
plt.xticks(rotation=60)
plt.title("MEJOR VENDEDOR")
plt.xlabel("Vendedores")
plt.ylabel("Monto")
plt.show()
# 'seller_anme' es el index
# RESOLUCIÓN ANALÍTICA
print("VARIACIÓN DE VENTAS MENSUAL")
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
VARIACIÓN DE VENTAS MENSUAL
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
# 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
# RESOLUCIÓN ANALÍTICA
# 5.1.A Ventas por país ordenados de forma descendente
print("VENTAS POR PAISES")
df6 = (my_df.groupby(by='country_name').sum()).sort_values('total_amount', ascending=False)
pd.options.display.float_format= '$ {:,.2f}'.format
print(df6[['quantity'] + ['total_amount']])
# 5.1.B Mayores Ventas de los 2 primeros países
print("TOP TWO DE VENTAS POR PAISES")
print(df6[['quantity'] + ['total_amount']].head(2))
df7=(df6[['quantity'] + ['total_amount']].head(2))
# 5.2 Producto mas vendido
print("PRODUCTO MAS VENDIDO")
df8 = (my_df.groupby(by='article_name').sum()).sort_values('quantity', ascending=False)
print(df8[['quantity'] ].head(1))
VENTAS POR PAISES
quantity total_amount
country_name
Brazil 2515 $ 441,271.85
Argentina 947 $ 205,832.78
Colombia 881 $ 177,514.29
Peru 1027 $ 161,421.12
Mexico 846 $ 138,619.99
Venezuela 320 $ 77,684.52
El Salvador 111 $ 57,391.26
Guatemala 202 $ 52,579.25
Honduras 303 $ 36,763.56
Costa Rica 145 $ 34,606.50
Chile 231 $ 24,660.98
Bolivia 181 $ 22,682.80
Uruguay 92 $ 17,843.09
Ecuador 129 $ 17,475.30
Paraguay 123 $ 8,195.12
Puerto Rico 12 $ 1,265.43
TOP TWO DE VENTAS POR PAISES
quantity total_amount
country_name
Brazil 2515 $ 441,271.85
Argentina 947 $ 205,832.78
PRODUCTO MAS VENDIDO
quantity
article_name
HDD 413
# 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
# RESOLUCIÓN ANALÍTICA
# 6.1 Evolución de Ventas por producto
print("EVOLUCIÓN DE VENTAS POR PRODUCTO")
df9 = (my_df.groupby(by='article_name').sum()).sort_values('total_amount', ascending=False)
pd.options.display.float_format= '$ {:,.2f}'.format
print(df9[['quantity'] + ['total_amount']])
# 6.2 Ventas semanales de los dos primeros paises
print("RANKING DE VENTAS SEMANALES POR PAISES")
print("VENTAS SEMANALES DE BRASIL")
# Brasil
df10 = my_df.loc[(my_df['country_name'] == 'Brazil')]
print(df10.groupby(['week']).agg({'total_amount':'sum'}).sort_values('total_amount', ascending=False))
df11=df10.groupby(['week']).agg({'total_amount':'sum'}).sort_values('week', ascending=True)
# Argentina
print("VENTAS SEMANALES DE ARGENTINA")
df12 = my_df.loc[(my_df['country_name'] == 'Argentina')]
print(df12.groupby(['week']).agg({'total_amount':'sum'}).sort_values('total_amount', ascending=False))
df13=df12.groupby(['week']).agg({'total_amount':'sum'}).sort_values('week', ascending=True)
EVOLUCIÓN DE VENTAS POR PRODUCTO
quantity total_amount
article_name
Full Pc 253 $ 538,335.93
Notebook 251 $ 251,000.00
Smartphone 290 $ 152,250.00
Chair 207 $ 69,477.48
Tablet 374 $ 48,620.00
Monitor 208 $ 47,840.00
Netbook 320 $ 46,400.00
Scanner 221 $ 40,885.00
Motherboard 291 $ 40,268.58
CPU 266 $ 37,138.92
Desk 223 $ 29,012.30
Video Card 209 $ 27,483.50
HDD 413 $ 22,558.06
Water Cooling 252 $ 17,010.00
Modem 244 $ 16,470.00
Power Supply 269 $ 11,822.55
Ram Memory 293 $ 10,533.35
Mouse 322 $ 9,756.60
Wi-Fi Card 141 $ 8,405.01
SDD 372 $ 8,184.00
Case 206 $ 7,807.40
Mesh Wi-Fi X 2 213 $ 6,922.50
Range Extender 281 $ 5,746.45
Headphones 239 $ 5,568.70
Webcam 229 $ 4,596.03
Keyboard 165 $ 3,729.00
Pci Express Port 291 $ 2,944.92
Heatsink 280 $ 2,800.00
Fan Cooler 205 $ 871.25
Usb Cable 273 $ 805.35
Sata Cable 264 $ 564.96
RANKING DE VENTAS SEMANALES POR PAISES
VENTAS SEMANALES DE BRASIL
total_amount
week
1 $ 165,289.90
2 $ 106,803.85
4 $ 89,836.60
3 $ 79,341.50
VENTAS SEMANALES DE ARGENTINA
total_amount
week
2 $ 96,789.13
1 $ 63,760.48
3 $ 26,601.97
4 $ 18,681.20
# RESOLUCIÓN
# Mejor vendedor/producto. Mostrar importe/cantidad. Comparar 2 países (variable categórica)
# Resolución Analítica y Gráfica
# RESOLUCIÓN ANALÍTICA
# 7.1.A Ventas por Vendedor
print("VENTAS POR VENDEDOR")
df14 = (my_df.groupby(by='seller_name').sum()).sort_values('total_amount', ascending=False)
pd.options.display.float_format= '$ {:,.2f}'.format
print(df14[['quantity'] + ['total_amount']])
# 7.1.B Mejor Vendedor por Producto
print("MEJOR VENDEDOR POR PRODUCTO")
df15 = (my_df.groupby(['seller_name','article_name']).sum()).sort_values('total_amount', ascending=False)
pd.options.display.float_format= '$ {:,.2f}'.format
print(df15[['quantity'] + ['total_amount']].head(1))
# 7.2 Mejor Vendedor por los dos primeros paises en el ranking de ventas
print("MEJOR VENDEDOR DEL RANKING DE VENTAS POR PAISES")
print("VENTAS DE BRASIL POR VENDEDOR")
# Brasil
df16 = my_df[my_df['country_name'] == 'Brazil']
df17 = (df16.groupby(by='seller_name').sum()).sort_values('total_amount', ascending=False).index.values
pd.options.display.float_format= '$ {:,.2f}'.format
print(df16[['seller_name'] + ['total_amount']])
# Argentina
print("VENTAS ARGENTINA POR VENDEDOR")
df18 = my_df[my_df['country_name'] == 'Argentina']
df19 = (df18.groupby(by='seller_name').sum()).sort_values('total_amount', ascending=False).index.values
pd.options.display.float_format= '$ {:,.2f}'.format
print(df18[['seller_name'] + ['total_amount']])
VENTAS POR VENDEDOR
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
Aveline Swanwick 629 $ 118,874.33
Arnold Kilkenny 583 $ 94,552.04
Kati Innot 512 $ 83,704.62
Jase Doy 582 $ 80,628.31
Ewell Peres 496 $ 78,144.32
Onida Cosely 535 $ 77,373.37
Milly Christoffe 442 $ 61,733.69
Tobin Roselli 519 $ 56,984.42
Cornie Wynrehame 523 $ 52,253.57
Cirilo Grandham 470 $ 45,009.40
MEJOR VENDEDOR POR PRODUCTO
quantity total_amount
seller_name article_name
Janel O'Curran Full Pc 56 $ 119,157.36
MEJOR VENDEDOR DEL RANKING DE VENTAS POR PAISES
VENTAS DE BRASIL POR VENDEDOR
seller_name total_amount
3 Janel O'Curran $ 1,170.00
10 Cirilo Grandham $ 2.14
14 Milly Christoffe $ 44.25
15 Cornie Wynrehame $ 395.45
16 Arnold Kilkenny $ 12,766.86
.. ... ...
993 Oliviero Charkham $ 2,685.12
995 Kati Innot $ 67.50
996 Daisie Slograve $ 150.00
998 Vasily Danilyuk $ 1,820.00
999 Onida Cosely $ 264.00
[315 rows x 2 columns]
VENTAS ARGENTINA POR VENDEDOR
seller_name total_amount
11 Kati Innot $ 143.80
17 Ewell Peres $ 20.45
23 Onida Cosely $ 337.50
27 Janel O'Curran $ 270.00
33 Jase Doy $ 143.15
.. ... ...
943 Vasily Danilyuk $ 54.62
948 Arnold Kilkenny $ 227.50
976 Cornie Wynrehame $ 20.65
990 Cornie Wynrehame $ 553.52
991 Brockie Patience $ 158.20
[113 rows x 2 columns]