
π This article includes 3 downloadable practice files β
Advertisement
In this article
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