Storage Formats (CSV and Parquet)
Lesson opener
In one line: When CSV is acceptable and when it becomes a liability.
Why it matters: Format mistakes cause silent numeric bugs (phone numbers as floats, GSTINs as scientific notation).
Before this lesson: Data Analysis with Python / Python basics
Before you start
| Resource | Link |
|---|---|
| Previous | Batch vs streaming |
| Next | ETL with pandas |
| Prerequisites | Data Analysis with Python or Python basics |
| Time | ~55 minutes |
What you will learn
- When CSV is acceptable and when it becomes a liability
- Why columnar Parquet helps analytics scans
- How to read/write Parquet with pandas and pyarrow pins
- Schema, compression, and type pitfalls across tools
Pinned libraries for this course
Install the course pins once and reuse them across lessons:
pip install -r docs/dataeng/requirements.txtPinned in docs/dataeng/requirements.txt:
pandas==2.2.3
numpy==2.1.3
pyarrow==18.1.0Pin versions so teammates in Bengaluru, Pune, and Mumbai reproduce the same numbers. This lesson uses the Python standard library plus the pins above where shown. Each Python fence re-imports everything so scripts/test_course_code.py can run blocks in isolation.
Files are APIs
A Pune analyst emails orders_final.csv. A Bengaluru engineer loads it into a warehouse. A Mumbai data scientist opens it in pandas and silently gets different dtypes. Storage format choices are interface contracts: encoding, types, null markers, and whether the file is row-oriented or columnar.
WHY Format mistakes cause silent numeric bugs (phone numbers as floats, GSTINs as scientific notation).
WHEN At the boundary between systems — before the first production handoff.
Pinned for this course: pandas==2.2.3, numpy==2.1.3, pyarrow==18.1.0 (see docs/dataeng/requirements.txt).
Demo 1 — CSV round-trip hazards
# Offline demo: CSV can mangle identifiers that look numeric
import io
import pandas as pd
csv_text = "order_id,gstin,amount_inr\nBLR1001,29AAAAA0000A1Z5,1299.50\n"
df = pd.read_csv(io.StringIO(csv_text), dtype={"order_id": "string", "gstin": "string"})
print(df.dtypes)
assert str(df.loc[0, "gstin"]).startswith("29")
assert df.loc[0, "amount_inr"] == 1299.50
print(df)Without explicit dtypes, long numeric strings may lose precision. Prefer Parquet or explicit schema for identifiers.
Columnar Parquet for analytics
Parquet stores data by column with embedded schema and compression. Scanning amount_inr for a million Bengaluru orders need not read every city string. pandas uses pyarrow as the engine for Parquet I/O in modern versions.
WHY Columnar layout + compression cuts I/O for warehouse-style queries.
WHEN Large analytical tables, data lake zones, and cross-tool exchange (Spark, DuckDB, pandas).
Demo 2 — Write and read Parquet via BytesIO
# Offline demo: Parquet round-trip with pandas + pyarrow
import io
import pandas as pd
df = pd.DataFrame(
{
"order_id": pd.Series(["BLR-1", "PNQ-2", "BOM-3"], dtype="string"),
"city": pd.Series(["Bengaluru", "Pune", "Mumbai"], dtype="string"),
"amount_inr": [1299.0, 899.0, 1499.0],
}
)
buf = io.BytesIO()
df.to_parquet(buf, engine="pyarrow", index=False)
buf.seek(0)
back = pd.read_parquet(buf, engine="pyarrow")
print(back)
assert list(back["city"]) == ["Bengaluru", "Pune", "Mumbai"]
assert abs(back["amount_inr"].sum() - 3697.0) < 1e-9Demo 3 — Compare on-disk sizes (in-memory proxy)
# Offline demo: CSV vs Parquet byte sizes for repeated rows
import io
import pandas as pd
rows = [{"city": "Bengaluru", "sku": "TEE-RED", "qty": 1, "amount_inr": 799.0}] * 2000
df = pd.DataFrame(rows)
csv_buf = io.StringIO()
df.to_csv(csv_buf, index=False)
csv_bytes = len(csv_buf.getvalue().encode("utf-8"))
pq_buf = io.BytesIO()
df.to_parquet(pq_buf, engine="pyarrow", index=False)
pq_bytes = len(pq_buf.getvalue())
print({"csv": csv_bytes, "parquet": pq_bytes})
assert pq_bytes < csv_bytes
assert csv_bytes > 0Schema and nulls
Parquet carries types. CSV does not. Align null markers ("" vs \N vs null) across exporters from OMS and WMS vendors.
Demo 4 — Enforce dtypes before write
# Offline demo: cast before Parquet so readers agree
import io
import pandas as pd
raw = pd.DataFrame({"order_id": ["1", "2"], "amount_inr": ["100", "200.5"]})
typed = raw.astype({"order_id": "string", "amount_inr": "float64"})
buf = io.BytesIO()
typed.to_parquet(buf, engine="pyarrow", index=False)
buf.seek(0)
out = pd.read_parquet(buf, engine="pyarrow")
print(out.dtypes)
assert out["amount_inr"].dtype == "float64"
assert out["amount_inr"].sum() == 300.5Demo 5 — Column projection mindset
# Offline demo: select only needed columns (lake scan habit)
import pandas as pd
df = pd.DataFrame(
{
"order_id": ["BLR-1", "PNQ-2"],
"pii_phone": ["9999999999", "8888888888"],
"amount_inr": [100.0, 200.0],
}
)
safe = df[["order_id", "amount_inr"]]
print(safe.columns.tolist())
assert "pii_phone" not in safe.columns
assert safe["amount_inr"].sum() == 300.0Demo 6 — pyarrow version pin sanity
# Offline demo: import pyarrow and report version string shape
import pyarrow as pa
version = pa.__version__
parts = version.split(".")
print("pyarrow", version)
assert len(parts) >= 2
assert parts[0].isdigit()Indian workplace framing
GSTIN, UPI VPA, and phone fields belong in typed string columns — never floats. Festival CSV dumps balloon; Parquet (and compression) saves network when Pune and Bengaluru offices sync lakes over limited VPN links.
WHY Identifier corruption creates irreproducible reconciliations.
WHEN At ingest — cast once, store correctly, refuse silent coercions.
Failure modes with files
Teams in Bengaluru sometimes treat CSV as a database: append rows by hand, rename columns mid-week, and email the latest file without a checksum. That works until a Mumbai finance close depends on it. Prefer immutable dated paths such as orders/2026-09-18.parquet, schema checks at read time, and a written owner for every landing zone.
WHY Ad-hoc files become un-auditable shadow systems.
WHEN As soon as two teams share a folder or bucket prefix.
Compression choices matter less than consistent types. Document whether timestamps are UTC or IST. If a vendor only sends CSV, wrap it once into Parquet in your bronze zone and never re-parse the CSV in five notebooks.
Practice checklist: identifiers as strings; explicit engine="pyarrow"; column projection before sharing extracts; size and row-count metrics logged each run; a one-line schema changelog when columns appear or disappear. Pin pandas==2.2.3, numpy==2.1.3, and pyarrow==18.1.0 so Bengaluru and Pune notebooks match CI.
Explain it to a stakeholder
CSV is for humans and quick exports. Parquet is for machines that must scan columns, preserve types, and shrink storage bills. When a Noida analyst emails a 2 GB CSV of order lines, every open in Excel risks type coercion on phone numbers and GSTINs. When the same table sits as Parquet in object storage, a Bengaluru pipeline can read only the columns it needs and keep amount_inr as a float instead of a string with commas.
Tell finance: Parquet is not a proprietary lock-in for this course — it is an open columnar format read by pandas through the pinned pyarrow==18.1.0 engine. Tell compliance: schemas travel with the file more honestly than a headerless CSV dumped at 2 a.m.
WHY Format choice is a reliability and cost decision, not a fashion choice.
WHEN Before the first production extract lands in shared storage.
Demo 7 — Type preservation check after round-trip
# Offline demo: Parquet keeps dtypes better than stringly CSV habits
import io
import pandas as pd
src = pd.DataFrame(
{
"order_id": ["BLR-1", "PNQ-2"],
"amount_inr": [799.5, 499.0],
"qty": [1, 2],
}
)
buf = io.BytesIO()
src.to_parquet(buf, engine="pyarrow", index=False)
buf.seek(0)
back = pd.read_parquet(buf, engine="pyarrow")
print(back.dtypes.to_string())
assert str(back["amount_inr"].dtype).startswith("float")
assert back["qty"].tolist() == [1, 2]If stakeholders insist on CSV for partner handoff, keep Parquet as the system of record and export CSV as a derived artifact with an explicit schema note.
Partitioning without overengineering
For Indian retail volumes, partition by business date in IST first. Do not invent fifty nested folders on day one. Document timezone: a "day" that mixes UTC and IST will double-count or drop festival midnights. Pune and Mumbai teams should agree whether biz_date means order placed date or payment captured date.
WHY Bad partitions create expensive full scans and confused audits.
WHEN When designing the first silver table layout.
Verified against pandas 2.2.3, numpy 2.1.3, pyarrow 18.1.0 documentation, September 2026.
Test yourself
- Why can CSV corrupt a GSTIN-like identifier?
- What advantage does Parquet have for analytics scans?
- Which engine string does this course use for pandas Parquet I/O?
- True or false: Parquet files embed a schema.
- Name the three pinned packages in
docs/dataeng/requirements.txt. - Why exclude
pii_phonewhen writing an analytics extract? - In Demo 3, what do we compare between CSV and Parquet?
- Should phone numbers be stored as float64? Why or why not?
- What does
dtype={...}achieve inread_csv? - True or false: empty string and null always mean the same thing across vendors.