Sub topic 4
Compressing CSV Files and Choosing an Encoding
This chapter assumes you can write a CSV with to_csv, know the options from the previous chapters (index, sep, na_rep), and have pandas installed. You will shrink CSV output with compression and control how text is turned into bytes.
Why compress a CSV
A CSV is plain text, and plain text compresses well. Repeated column values and numbers often shrink by a large factor. Compression saves disk space and speeds up transfers. The cost is that people can no longer open the file by double-clicking it in a text editor, and each read or write spends some CPU time.
Compression inferred from the file name
By default, to_csv uses compression="infer". It looks at the file extension and picks a method.
| Extension | Method | Notes |
|---|---|---|
| `.gz` | gzip | Widely supported, good default |
| `.bz2` | bzip2 | Smaller files, slower |
| `.zip` | zip | Opens easily on desktop systems |
| `.xz` | xz | Small files, slow to write |
| `.zst` | zstandard | Fast, needs the `zstandard` package |
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 3],
"customer": ["Ana", "Ben", None],
"amount": [19.99, 5.5, None],
"ordered_at": pd.to_datetime(["2026-01-05", "2026-01-06", "2026-01-07"]),
})
df.to_csv("orders.csv.gz", index=False)
back = pd.read_csv("orders.csv.gz", parse_dates=["ordered_at"])
print(back.dtypes)read_csv also infers compression from the extension, so the round trip needs no extra argument. The parse_dates argument is still required. Compression does not change which dtypes a CSV can store.
Setting compression explicitly
If the file name has no helpful extension, pass the method yourself. For more control, pass a dictionary. The method key names the algorithm, and the other keys go to the underlying library.
df.to_csv("orders.dat", index=False, compression="gzip")
df.to_csv(
"orders_fast.csv.gz",
index=False,
compression={"method": "gzip", "compresslevel": 1},
)A low compresslevel writes faster and produces a larger file. A high level does the reverse.
Encoding: text to bytes
An encoding is the rule that maps characters to bytes. The encoding argument of to_csv sets that rule. The default is "utf-8", which covers every character and works on all modern systems. In most cases you should leave it alone.
people = pd.DataFrame({"name": ["Zoë", "Søren", "李雷"], "score": [3, 4, 5]})
people.to_csv("people.csv", index=False, encoding="utf-8")Problems appear when the reader expects something else. Two cases come up often:
- Excel on Windows shows garbled accents. Excel may guess a legacy encoding for a plain UTF-8 file. Writing with
encoding="utf-8-sig"adds a byte order mark (BOM), a short marker at the start of the file. It tells Excel the file is UTF-8. - A legacy system requires a specific encoding, such as
"latin-1"or"cp1252". These encodings hold only a limited set of characters.
people.to_csv("people_excel.csv", index=False, encoding="utf-8-sig")When you read the file back, give read_csv the same encoding. If you wrote utf-8-sig, reading it with encoding="utf-8-sig" strips the BOM. If you read it as plain utf-8, the first column name gains an invisible \ufeff character.
How the pieces fit
Encoding happens before compression. The compressed file holds encoded bytes, so the reader must decompress first and then decode with the right encoding.
Common errors
- Wrong extension, uncompressed content. Naming a file
.gzwhile passingcompression=Noneproduces plain text with a misleading name. Readers that infer compression will fail. - Missing library. Zstandard needs the
zstandardpackage. Install it withpip install zstandard. - Mismatched read and write encodings. This shows up as
UnicodeDecodeErroror as strange characters in the data.
Exercise
You write a DataFrame with df.to_csv("data.csv.gz", index=False, encoding="utf-8-sig"). Name the compression method pandas uses, and say what you must pass to read_csv so the first column name has no invisible BOM character.
Show answer
pandas infers gzip from the .gz extension. Pass encoding="utf-8-sig" to read_csv, for example pd.read_csv("data.csv.gz", encoding="utf-8-sig"). Compression is inferred again on reading.
Exercise
Why does the diagram place encoding before compression, and what does that mean for a reader of the file?
Show answer
pandas first turns the text into bytes with the chosen encoding, then compresses those bytes. A reader must decompress first and then decode the bytes with the same encoding.