πRead
read_csv / json_normalize
πInspect
shape, dtypes, isna, value_counts
π§ΉClean
duplicates, types, text, missing
πShape
filter, groupby, merge, dates
πΎWrite
Parquet
Read and look
import pandas as pd
df = pd.read_csv("data/orders.csv")
print(df.shape) # (rows, columns)
print(df.head(4))(10, 7) order_id customer_id product quantity price status order_date 0 101 1.0 Headphones 1 1999 DELIVERED 2026-04-01 1 102 2.0 Smartwatch 1 4999 delivered 2026-04-01 2 103 1.0 Charger 3 499 DELIVERED 2026-04-03 3 104 3.0 Smartwatch 1 4999 CANCELLED 2026-04-05
print(df.dtypes)order_id int64 customer_id float64 product str quantity str price int64 status str order_date str dtype: object
pandas guessed types: customer_id became float64 because one value is missing, and quantity is text because of the value βtwoβ. Always check dtypes; wrong types are the root of many pipeline bugs.
print(df.isna().sum()) # missing values per column
print("duplicate rows:", df.duplicated().sum())
print(df["status"].value_counts())order_id 0 customer_id 1 product 0 quantity 0 price 0 status 0 order_date 0 dtype: int64 duplicate rows: 1 status DELIVERED 6 PLACED 2 delivered 1 CANCELLED 1 Name: count, dtype: int64
One missing customer, one duplicate row, and βdeliveredβ vs βDELIVEREDβ counted separately. Now we know what to fix.
Clean it
clean = (
df.drop_duplicates() # exact duplicate rows
.assign(
product=lambda d: d["product"].str.strip(),
status=lambda d: d["status"].str.upper(),
quantity=lambda d: pd.to_numeric(d["quantity"], errors="coerce"), # 'two' β NaN
order_date=lambda d: pd.to_datetime(d["order_date"]),
)
.dropna(subset=["customer_id", "quantity"]) # drop rows we can't use
.astype({"customer_id": "int64", "quantity": "int64"})
)
clean["amount"] = clean["quantity"] * clean["price"]
print(clean.shape)
print(clean[["order_id", "customer_id", "product", "status", "amount"]])(7, 8) order_id customer_id product status amount 0 101 1 Headphones DELIVERED 1999 1 102 2 Smartwatch DELIVERED 4999 2 103 1 Charger DELIVERED 1497 3 104 3 Smartwatch CANCELLED 4999 4 105 4 Headphones DELIVERED 1999 5 106 2 Laptop Stand DELIVERED 1299 6 107 5 Phone Case PLACED 1196
.assign(col=lambda d: ...)adds or replaces columns in a readable chain..str.strip(),.str.upper(): string methods on a whole column at once.pd.to_numeric(..., errors="coerce")turns βtwoβ into NaN sodropnacan remove it (in a real job, save those rows as rejects first).- 10 rows in, 7 clean rows out: the duplicate, the missing customer and the bad quantity are gone.
Filter rows
delivered = clean[(clean["status"] == "DELIVERED") & (clean["amount"] > 1000)]
print(delivered[["order_id", "product", "amount"]])order_id product amount 0 101 Headphones 1999 1 102 Smartwatch 4999 2 103 Charger 1497 4 105 Headphones 1999 5 106 Laptop Stand 1299
Group and aggregate
by_product = (
clean[clean["status"] == "DELIVERED"]
.groupby("product", as_index=False)
.agg(revenue=("amount", "sum"), orders=("order_id", "count"))
.sort_values("revenue", ascending=False)
)
print(by_product)product revenue orders 3 Smartwatch 4999 1 1 Headphones 3998 2 0 Charger 1497 1 2 Laptop Stand 1299 1
Join with merge
import json
with open("data/customers.json", encoding="utf-8") as f:
customers = pd.json_normalize(json.load(f)) # nested JSON β flat columns
print(customers.columns.tolist())
joined = clean.merge(customers[["customer_id", "name", "city"]], on="customer_id", how="left")
joined["city"] = joined["city"].fillna("Unknown")
print(joined[["order_id", "name", "city", "amount"]])['customer_id', 'name', 'city', 'contact.email', 'contact.phone'] order_id name city amount 0 101 Asha Kolkata 1999 1 102 Rahul Mumbai 4999 2 103 Asha Kolkata 1497 3 104 Priya Bengaluru 4999 4 105 Imran Delhi 1999 5 106 Rahul Mumbai 1299 6 107 Meera Unknown 1196
json_normalize flattened the nested contact info into contact.email and contact.phone. merge(..., how="left") is a LEFT JOIN; Meera's missing city became βUnknownβ with fillna.
| SQL | pandas |
|---|---|
| SELECT a, b | df[['a', 'b']] |
| WHERE x > 5 | df[df['x'] > 5] |
| GROUP BY k + SUM(v) | df.groupby('k')['v'].sum() |
| LEFT JOIN β¦ ON id | df.merge(other, on='id', how='left') |
| ORDER BY v DESC | df.sort_values('v', ascending=False) |
| COALESCE(c, 'x') | df['c'].fillna('x') |
| DISTINCT | df.drop_duplicates() |
| ROW_NUMBER() OVER (β¦) | df.groupby('k').cumcount() + 1 |
Dates
monthly = (
clean.assign(month=clean["order_date"].dt.to_period("M"))
.groupby("month")["amount"].sum()
)
print(monthly)month 2026-04 17988 Freq: M, Name: amount, dtype: int64
After to_datetime, the .dt accessor gives year, month, weekday and periods. All our clean orders are from April.
Write Parquet
clean.to_parquet("orders_clean.parquet", index=False)
back = pd.read_parquet("orders_clean.parquet")
print(back.dtypes[["order_date", "amount"]]) # types survive, unlike CSVorder_date datetime64[us] amount int64 dtype: object
import os
import numpy as np
rng = np.random.default_rng(42) # 100,000 realistic, varied orders
n = 100_000
big = pd.DataFrame({
"order_id": np.arange(1, n + 1),
"customer_id": rng.integers(1, 20_000, n),
"product": rng.choice(["Headphones", "Smartwatch", "Charger", "Laptop Stand", "Phone Case"], n),
"quantity": rng.integers(1, 5, n),
"price": rng.choice([1999, 4999, 499, 1299, 299], n),
"status": rng.choice(["DELIVERED", "PLACED", "CANCELLED", "RETURNED"], n, p=[0.8, 0.1, 0.06, 0.04]),
"order_date": pd.Timestamp("2026-01-01") + pd.to_timedelta(rng.integers(0, 180, n), unit="D"),
})
big.to_csv("big.csv", index=False)
big.to_parquet("big.parquet", index=False)
print(f"csv: {os.path.getsize('big.csv') / 1e6:.1f} MB")
print(f"parquet: {os.path.getsize('big.parquet') / 1e6:.1f} MB")csv: 4.9 MB parquet: 1.1 MB
Same 100,000 orders: Parquet is about 4.5Γ smaller than CSV here, keeps the types, and reads only the columns a query needs. That's why lakehouses store Parquet (Delta Lake is Parquet plus a log).
Files bigger than memory: chunks
total = 0
for chunk in pd.read_csv("data/orders.csv", chunksize=4): # process a big file piece by piece
chunk["quantity"] = pd.to_numeric(chunk["quantity"], errors="coerce")
total += (chunk["quantity"] * chunk["price"]).sum()
print(f"chunk of {len(chunk)} rows, running total {total:,.0f}")chunk of 4 rows, running total 13,494 chunk of 4 rows, running total 19,184 chunk of 2 rows, running total 24,183
When pandas isn't enough
| Data size | Tool |
|---|---|
| Up to a few GB | pandas |
| Up to tens of GB on one machine | Polars or DuckDB (fast, multi-core) |
| Bigger, or many files every day | PySpark / Databricks, or SQL in a warehouse |
π― Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1What is a DataFrame?Fresher+
Q2How do you handle missing values in pandas?1β3 yrs+
Q3merge vs join vs concat?1β3 yrs+
Q4How do you process a file larger than memory in pandas?1β3 yrs+
Q5What is copy-on-write in pandas 3?3+ yrs+
Q6pandas vs PySpark?3+ yrs+
Key takeaways
- βpandas turns cleaning and reshaping into short, readable chains.
- βInspect types first; most bugs come from wrong dtypes.
- βParquet beats CSV for pipeline output.
- βNext: loading data into PostgreSQL from Python.
Frequently asked questions
What is pandas?
A Python library for working with tables (DataFrames) in memory: read files, clean, filter, group, join and write them, with SQL-like operations in a few lines.
pandas or PySpark?
pandas runs on one machine and is great up to a few GB. PySpark splits work across a cluster for bigger data. Their ideas are similar, so pandas skills transfer. Polars and DuckDB are fast single-machine alternatives.
Why did customer_id become a float?
A column of integers with a missing value can't be a plain int64, so pandas uses float64 with NaN. After dropping missing rows, convert back with astype('int64'), or use the nullable 'Int64' type.
Why write Parquet instead of CSV?
Parquet keeps column types (dates stay dates), is compressed and columnar, so it's several times smaller and much faster to read. Every lakehouse and warehouse reads it.
What changed in pandas 3?
Copy-on-write is always on (no more SettingWithCopyWarning confusion), and text columns use a dedicated string type ('str') by default. This lesson's output comes from pandas 3.1.
π§ Quick check: pandas
1. pd.to_numeric(col, errors='coerce') turns 'two' into...
2. How do you keep rows where status is DELIVERED AND amount > 1000?
3. SQL's LEFT JOIN in pandas is...
4. Best way to process a CSV bigger than memory with pandas?
Checking your accessβ¦