26. How to Read APIs, JSON and Zipped CSVs into pandas
26.5 Zipped CSVs into pandas
Why. Email caps and GitHub dislike huge CSVs. Ops sends orders_oct.csv.zip. You still want the same cleaning pipeline.
What.
pd.read_csv("file.csv.zip")often works (pandas detects zip compression).- Or
compression="zip"explicitly. - For a zip with many members, open with
zipfileand pick the CSV name.
How.
Read a classroom zip
- Save the zip under
data/raw/. - Try
pd.read_csv(path)on the.csv.zip. - If multiple files inside,
ZipFile.namelist()and choose one. - Same dtype /
dayfirsthabits as Chapter 10. - Write a clean extract to
data/clean/uncompressed for daily work if you prefer.
Worked example A — Build + read a zip (copy-paste).
import zipfile
from pathlib import Path
import pandas as pd
Path("data/raw").mkdir(parents=True, exist_ok=True)
csv_path = Path("data/raw/orders_mini.csv")
csv_path.write_text(
"order_id,city,amount_inr\nBLK-50,Pune,189\nBLK-51,Nashik,95\n",
encoding="utf-8",
)
zip_path = Path("data/raw/orders_mini.csv.zip")
with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as z:
z.write(csv_path, arcname="orders_mini.csv")
df = pd.read_csv(zip_path)
print(df)
Worked example B — Explicit compression.
df2 = pd.read_csv(zip_path, compression="zip")
print(df2.equals(df))
Worked example C — Multiple members.
with zipfile.ZipFile(zip_path) as z:
print(z.namelist())
Ravindra Bagale's Tip
A file named .csv.zip is a CSV inside a zip, and pd.read_csv() can usually read it directly. If the zip holds more than one file, list them with namelist() and pick the CSV yourself, because zips often also carry a README or junk folders. Keep the same dtype and date habits that you use for a normal CSV.
Ravindra Bagale's Tip – मराठी
.csv.zip नावाची file म्हणजे zip मध्ये ठेवलेली CSV, आणि pd.read_csv() ती बहुतेक वेळा थेट वाचू शकतो. Zip मध्ये एकापेक्षा जास्त files असतील तर namelist() ने त्यांची यादी पाहा आणि CSV स्वतः निवडा, कारण zip मध्ये अनेकदा README किंवा junk folders सुद्धा असतात. साध्या CSV साठी वापरता त्याच dtype आणि date च्या सवयी इथेही पाळा.
Ravindra Bagale's Tip – हिंदी
.csv.zip नाम की file असल में zip के अंदर रखी CSV है, और pd.read_csv() उसे ज़्यादातर सीधे पढ़ लेता है। अगर zip में एक से ज़्यादा files हों, तो namelist() से उनकी list देखो और CSV ख़ुद चुनो, क्योंकि zip में अक्सर README या junk folders भी होते हैं। सामान्य CSV के लिए जो dtype और date की आदतें रखते हो, वही यहाँ भी रखो।