Python Intermediate Lesson 5: pandas in Depth – Merge, GroupBy and Pivot Tables

Python Intermediate Lesson 5: pandas in Depth - Merge, GroupBy and Pivot Tables 1

πŸ“Ž This article includes 3 downloadable practice files ↓

⏱ 2 min read

πŸ“˜ Python Intermediate Course Β· Lesson 5 of 10

Advertisement
In this article
  1. 1. Clean types first
  2. 2. Merge (the pandas VLOOKUP)
  3. 3. GroupBy with named aggregations
  4. 4. Pivot tables
  5. Practice

1. Clean types first

sales["date"] = pd.to_datetime(sales["date"], format="%Y-%m-%d", errors="coerce")
sales["qty"]  = pd.to_numeric(sales["qty"], errors="coerce")
sales = sales.dropna(subset=["date", "qty"])     # the 2 bad rows become NaT/NaN, then go

2. Merge (the pandas VLOOKUP)

prod = prod.rename(columns={"name": "product"})   # customers also have "name"!
df = sales.merge(cust, on="customer_id", how="left").merge(prod, on="code", how="left")
⚠️ When both tables have a column with the same name, pandas renames them name_x and name_y and your later df["name"] fails with KeyError. That’s exactly what happened while we wrote this lesson. Rename before merging.

3. GroupBy with named aggregations

df.groupby("region").agg(invoices=("invoice", "count"),
                         amount=("amount", "sum"),
                         avg=("amount", "mean")).round(0)

4. Pivot tables

df["month"] = df["date"].dt.strftime("%Y-%m")
df.pivot_table(index="category", columns="month", values="amount", aggfunc="sum", fill_value=0)
πŸ’‘ how="left" keeps every sale even if a code is missing from the product list; check with df["price"].isna().sum() afterwards. Silent row loss from an inner join is the most common pandas reporting error.

Practice

Unzip the practice data into a folder, put this lesson’s script in the same folder and run it (python pyi-NN.py). Compare with the expected output file. Then change one thing (a filter, a column, a format) and predict the new output before you run it.

πŸ“Ž Practice files for this article

⬇ Download all 3 files (ZIP Β· 4 KB)

  • 🐍
    Lesson 5 scriptThe complete script from this lesson, ready to run.
    ⬇ PY Β· 1 KB
  • πŸ“„
    Expected outputWhat the script printed when we ran it, to compare with yours.
    ⬇ TXT Β· 656 B
  • πŸ—‚οΈ
    Practice data (zip)sales.csv (120 invoices, 2 deliberately broken rows), customers.csv, products.json, statement.txt, rates.json and 3 monthly CSVs.
    ⬇ ZIP Β· 4 KB

Free to use for learning. Files with macros (.bas) are plain text β€” import them with Alt+F11 β†’ File β†’ Import File, and always test on a copy.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free Β· AI can be wrong

Leave a Reply

Your email address will not be published. Required fields are marked *