3. Connecting Data Sources (CSV, Excel, APIs & SQL)
Reading & Writing CSV, Excel, JSON & SQL Pipelines
Ingest and export analytics data across formats cleanly: stream huge CSVs with chunksize, read Excel sheets with openpyxl, flatten nested JSON, and query SQLite/PostgreSQL into DataFrames.
- Load CSV, Excel, and JSON cleanly while controlling memory via usecols, dtype, and chunksize
- Query SQL databases directly into Python/Pandas using parameterized read_sql()
- Flatten nested JSON API responses using json_normalize()
In real organizations, data never arrives in one tidy file. Marketing sends a multi-sheet .xlsx workbook, your warehouse stores historical orders in PostgreSQL or SQLite, your app streams 500 MB event logs as .csv, and Stripe webhooks emit deeply nested .json.
Building resilient ETL (Extract, Transform, Load) pipelines means knowing how to read each source cleanly without running out of memory, losing leading zeros in IDs, or opening SQL injection holes.
Python RAM (Temporary)
tasks = [...]
Hard Drive (Permanent)
tasks.json / .csv
Stream large CSVs with chunksize= or filter inside SQL before loading into Python RAM so laptops and servers never run out of memory.
1. Memory-Safe CSV & Multi-Sheet Excel Loading
Calling pd.read_csv("events.csv") with no options loads every column as wide 64-bit types and guesses dtypes—which can freeze an 8 GB laptop on a 2 GB export. Control memory upfront with four flags:
import pandas as pd
# 1. Load only required columns, preserve string IDs, and parse dates
orders = pd.read_csv(
"orders.csv",
usecols=["order_id", "zip_code", "ordered_at", "amount"],
dtype={"order_id": "string", "zip_code": "string"}, # Keeps "02139" instead of 2139!
parse_dates=["ordered_at"],
)
# 2. Stream a multi-GB CSV in bounded chunks (constant RAM!)
total_revenue = 0.0
for chunk in pd.read_csv("huge_events.csv", chunksize=50_000):
paid = chunk.loc[chunk["status"] == "paid"]
total_revenue += paid["amount"].sum()Multi-Sheet Excel Workbooks (openpyxl)
Finance teams love Excel workbooks with tabs like Q3_Summary, Q4_Summary, and Notes. Install openpyxl (pip install openpyxl), then read specific tabs or all sheets at once:
# Read one specific sheet
df_q4 = pd.read_excel("financials.xlsx", sheet_name="Q4_Summary", engine="openpyxl")
# Read ALL sheets into a dict {sheet_name: DataFrame}
all_sheets = pd.read_excel("financials.xlsx", sheet_name=None, engine="openpyxl")
combined = pd.concat(
[sheet.assign(tab_name=name) for name, sheet in all_sheets.items()],
ignore_index=True,
)If a CSV has postal codes like "02139" or SKU codes like "00481", pd.read_csv() infers integer and silently strips leading zeros (2139). Always pass dtype={"zip_code": "string"} for IDs, phone numbers, and postal codes!
2. Bridging SQL Databases & Python (pd.read_sql_query)
Let the database engine filter and aggregate billions of rows with WHERE and GROUP BY before pulling data into Python RAM. Whenever a query includes dynamic dates or filters, always use parameterized queries (params=):
import sqlite3
import pandas as pd
min_date = "2026-11-01"
# GOOD: Parameterized query with ? placeholder (SQLite) or %s (PostgreSQL)
with sqlite3.connect("academy.db") as conn:
df = pd.read_sql_query(
"""
SELECT course_id, COUNT(*) AS enrollments
FROM enrollments
WHERE enrolled_on >= ?
GROUP BY course_id
""",
conn,
params=(min_date,),
)Writing f"WHERE enrolled_on >= '{min_date}'" breaks on quotes in names (like O'Brien) and creates a SQL injection vulnerability if min_date comes from user input or an external file. Always bind values with params=(...).
3. Flattening Nested JSON APIs (pd.json_normalize)
REST APIs and webhook logs rarely return flat rows—they nest objects and lists inside each record:
payload = [
{
"order_id": 101,
"customer": {"name": "Maya", "city": "Toronto"},
"items": [{"sku": "KB-1", "qty": 1}, {"sku": "USB-2", "qty": 2}],
}
]
# Flatten nested dicts into customer.name, customer.city
flat_orders = pd.json_normalize(payload, sep=".")
# Or explode nested line-item arrays while carrying parent metadata!
line_items = pd.json_normalize(
payload,
record_path="items",
meta=["order_id", ["customer", "name"]],
)Source Selection Quick Reference
| Format | Best Pandas / Stdlib Tool | Key Safety Flag |
|---|---|---|
| CSV (small–medium) | pd.read_csv() | usecols=, dtype=, parse_dates= |
| CSV (multi-GB) | pd.read_csv(..., chunksize=50_000) | Process & aggregate per chunk |
Excel (.xlsx) | pd.read_excel(..., engine="openpyxl") | sheet_name=None for all tabs |
| SQL (SQLite/Postgres) | pd.read_sql_query(..., params=...) | Parameterized ? or %s placeholders |
| Nested JSON | pd.json_normalize(..., record_path=..., meta=...) | Explode nested item lists cleanly |
Try It Yourself in the Playground
Run an end-to-end Nested JSON → SQLite → SQL Aggregation → CSV Export mini-ETL pipeline right inside the browser sandbox:
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: What happens when you pass chunksize=10_000 to pd.read_csv(...)?
Quick Checkpoints
Why should you pass usecols=[...] when calling pd.read_csv() on wide 80-column datasets?
How do you safely filter a pd.read_sql_query() call with a dynamic Python variable min_date?
A CSV has a zip_code column containing values like '02139' and '07030'. How do you stop pd.read_csv() from dropping the leading zeros?