Learning by Doing

Python Topic #1 — Learning by Doing

Abrir un Excel real en Google Colab, calcular ventas y crear primeros análisis de negocio.
Open a real Excel file in Google Colab, calculate sales, and create the first business analyses.

🎥 Práctica grabada

🎥 Recorded practice

Learning by Doing Topic #1

Este material acompaña la práctica grabada paso a paso. Puedes ver el video en YouTube y usar esta guía para copiar los scripts mientras avanzas.

Ver práctica en YouTube
Learning by Doing Topic #1

This material supports the step-by-step recorded practice. You can watch the video on YouTube and use this guide to copy the scripts as you move forward.

Watch practice on YouTube

Guion de apertura

Opening script

Idea central: Hoy no vamos a aprender Python de forma tradicional. Vamos a usar Python para resolver un problema real con datos reales.
Main idea: Today we are not going to learn Python in the traditional way. We are going to use Python to solve a real problem with real data.

“Tengo un archivo Excel basado en Northwind. No tengo nada preparado en Python. Vamos a subirlo a Google Colab, explorarlo y empezar a responder preguntas de negocio.”

“I have an Excel file based on Northwind. I do not have anything prepared in Python. We are going to upload it to Google Colab, explore it, and start answering business questions.”

Antes de comenzar — aviso importante

Before starting — important warning

⚠️ Aviso de seguridad y ambiente de producción: Este ejercicio es solamente para aprendizaje y práctica controlada en Google Colab con datos de ejemplo. No ejecutes estos scripts en ambientes de producción, carpetas reales de trabajo, sistemas corporativos, servidores compartidos ni archivos oficiales sin autorización. Antes de usar cualquier código con datos reales, valida permisos, realiza backups, prueba primero en una copia, usa datos no confidenciales, respeta las políticas de ciberseguridad de tu organización y sigue los protocolos de cambio, privacidad y cumplimiento aplicables.
⚠️ Security and production-environment warning: This exercise is only for learning and controlled practice in Google Colab using sample data. Do not run these scripts in production environments, real work folders, corporate systems, shared servers, or official files without authorization. Before using any code with real data, validate permissions, create backups, test on a copy first, use non-confidential data, follow your organization’s cybersecurity policies, and comply with all applicable change-control, privacy, and compliance protocols.

1. Subir el archivo Excel a ColabUpload the Excel file to Colab

Objetivo: cargar Northwinds.xlsx desde la computadora.
Goal: upload Northwinds.xlsx from your computer.
from google.colab import files

uploaded = files.upload()

Luego selecciona el archivo: Northwinds.xlsx.

Then select the file: Northwinds.xlsx.

2. Verificar que el archivo llegóVerify that the file was uploaded

Objetivo: confirmar que Colab reconoce el archivo.
Goal: confirm that Colab recognizes the file.
import os

os.listdir()

“En el mundo real no asumimos que el archivo está listo. Primero validamos.”

“In the real world, we do not assume the file is ready. First, we validate.”

3. Leer el ExcelRead the Excel file

Objetivo: convertir el Excel en un DataFrame de Pandas.
Goal: convert the Excel file into a Pandas DataFrame.
import pandas as pd

df = pd.read_excel("Northwinds.xlsx")

df.head()

4. Listar columnasList columns

Objetivo: saber qué campos trae el archivo.
Goal: understand which fields are included in the file.
for col in df.columns:
    print(col)

5. Revisar cantidad de filas y columnasCheck rows and columns

Objetivo: entender el tamaño del dataset.
Goal: understand the size of the dataset.
df.shape

6. Calcular SalesCalculate Sales

Objetivo: crear una métrica de negocio.
Goal: create a business metric.
df["Sales"] = (
    df["Quantity"]
    * df["UnitPrice"]
    * (1 - df["Discount"])
)

df[["CompanyName", "ProductName", "UnitPrice", "Quantity", "Discount", "Sales"]].head()

“Ahora no estamos aprendiendo sintaxis. Estamos creando una métrica real de ventas.”

“Now we are not learning syntax. We are creating a real sales metric.”

7. Top 10 ventasTop 10 sales

Objetivo: mostrar las 10 ventas individuales más altas del archivo.
Goal: show the 10 highest individual sales in the file.

“Aquí ya empezamos a pensar como analistas: no miramos todas las filas; buscamos las transacciones que más pesan en el negocio.”

“Here we start thinking like analysts: we do not look at every row; we look for the transactions that matter the most to the business.”

top10_sales = (
    df[[
        "CompanyName",
        "ProductName",
        "UnitPrice",
        "Quantity",
        "Discount",
        "Sales"
    ]]
    .sort_values(by="Sales", ascending=False)
    .head(10)
)

top10_sales

8. Top 10 ventas con formato profesionalTop 10 sales with professional formatting

Objetivo: presentar el Top 10 con Sales en formato currency y CompanyName alineado a la izquierda.
Goal: present the Top 10 with Sales in currency format and CompanyName aligned to the left.
top10_sales.style.format({
    "UnitPrice": "${:,.2f}",
    "Discount": "{:.0%}",
    "Sales": "${:,.2f}"
}).set_properties(
    subset=["CompanyName", "ProductName"],
    **{"text-align": "left"}
).set_properties(
    subset=["UnitPrice", "Quantity", "Discount", "Sales"],
    **{"text-align": "right"}
)

9. Ventas totales por compañíaTotal sales by company

Objetivo: agregar las ventas por cliente.
Goal: aggregate sales by customer/company.
sales_by_company = (
    df.groupby("CompanyName")["Sales"]
      .sum()
      .reset_index()
      .sort_values(by="Sales", ascending=False)
)

sales_by_company.head(10)

10. Mostrar Sales como currencyDisplay Sales as currency

Objetivo: presentar la tabla con formato profesional.
Goal: present the table with professional formatting.
sales_by_company.style.format({
    "Sales": "${:,.2f}"
}).set_properties(
    subset=["CompanyName"],
    **{"text-align": "left"}
).set_properties(
    subset=["Sales"],
    **{"text-align": "right"}
)

11. Bottom 5 compañías por ventasBottom 5 companies by sales

Objetivo: identificar clientes con menor volumen de ventas.
Goal: identify customers with the lowest sales volume.
bottom5_sales = (
    sales_by_company
    .sort_values(by="Sales", ascending=True)
    .head(5)
)

bottom5_sales.style.format({
    "Sales": "${:,.2f}"
})

12. Promedio de ventas por compañíaAverage sales by company

Objetivo: calcular una referencia general.
Goal: calculate a general reference point.
average_sales = sales_by_company["Sales"].mean()

print(f"Average Sales per Company: ${average_sales:,.2f}")

13. Desviación estándar por compañíaStandard deviation by company

Objetivo: medir la dispersión de ventas entre clientes.
Goal: measure the dispersion of sales across customers.
avg_sales = sales_by_company["Sales"].mean()
std_sales = sales_by_company["Sales"].std()

lower_limit = avg_sales - std_sales
upper_limit = avg_sales + std_sales

print(f"Average Sales: ${avg_sales:,.2f}")
print(f"Standard Deviation: ${std_sales:,.2f}")
print(f"Typical Range: ${lower_limit:,.2f} to ${upper_limit:,.2f}")

14. Ventas totales por productoTotal sales by product

Objetivo: cambiar la perspectiva de cliente a producto.
Goal: shift the analysis perspective from customer to product.
sales_by_product = (
    df.groupby("ProductName")["Sales"]
      .sum()
      .reset_index()
      .sort_values(by="Sales", ascending=False)
)

sales_by_product.head(10)

15. Promedio y desviación estándar por productoAverage and standard deviation by product

Objetivo: analizar comportamiento de ventas por producto.
Goal: analyze sales behavior by product.
avg_product_sales = sales_by_product["Sales"].mean()
std_product_sales = sales_by_product["Sales"].std()

lower_product_limit = avg_product_sales - std_product_sales
upper_product_limit = avg_product_sales + std_product_sales

print(f"Average Sales per Product: ${avg_product_sales:,.2f}")
print(f"Standard Deviation: ${std_product_sales:,.2f}")
print(f"Typical Range: ${lower_product_limit:,.2f} to ${upper_product_limit:,.2f}")

Cierre sugerido

Suggested closing

“En este primer topic no memorizamos Python. Tomamos un Excel real, lo subimos a Colab, creamos una métrica de ventas y respondimos preguntas de negocio. Eso es Learning by Doing.”

“In this first topic, we did not memorize Python. We took a real Excel file, uploaded it to Colab, created a sales metric, and answered business questions. That is Learning by Doing.”