Sub topic 4
Compressing CSV files and choosing an encoding
This chapter covers two settings of to_csv that decide how a file is stored on disk: compression, which changes its size, and encoding, which changes how text becomes bytes. It assumes you can already write a CSV with to_csv and control the index, header, and separator. It also assumes you know what a pandas dtype is and can install packages with pip.
Compression in to_csv
A CSV is plain text, and plain text compresses well. Repeated column values, similar numbers, and repeated delimiters all shrink. A compressed CSV is still one file in the same layout. You only add a compression step on write and the matching decompression step on read.
The compression argument of to_csv has a default of "infer". With it, pandas looks at the file extension and picks the method. You do not set anything else.
import os
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 100_000
df = pd.DataFrame({
"order_id": np.arange(n),
"country": rng.choice(["DE", "FR", "ES"], n),
"amount": rng.normal(50, 10, n).round(2),
})
for name in ["big.csv", "big.csv.gz", "big.csv.bz2", "big.csv.xz"]:
df.to_csv(name, index=False)
print(f"{name:12} {os.path.getsize(name):>10,} bytes")The exact sizes depend on your data, but the compressed files will be a fraction of big.csv. Typical ordering is gzip largest of the three, then bz2, then xz smallest.
Which methods exist
| Extension | `compression` value | Extra package | Notes |
|---|---|---|---|
| `.gz` | `"gzip"` | None | Fast, widely supported. A good default. |
| `.bz2` | `"bz2"` | None | Smaller than gzip, slower to write. |
| `.xz` | `"xz"` | None | Often the smallest, and the slowest. |
| `.zip` | `"zip"` | None | Holds one file inside an archive. |
| `.zst` | `"zstd"` | `zstandard` | Fast, with a good ratio. Install with `pip install zstandard`. |
| `.tar`, `.tar.gz` | `"tar"` | None | Available in recent pandas versions. Check your version's documentation. |
Every method in the table except zstd ships with the Python standard library. Choose a method by who reads the file. Gzip opens almost anywhere, including shell tools such as zcat and most databases and data tools. Use xz or zstd only when you control the reader.
Setting the method explicitly
Inference only works when the extension matches. If the file name does not end in a known extension, pandas writes uncompressed text and does not warn you. Pass the method yourself in that case:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": ["x", "y", "z"]})
df.to_csv("export.dat", index=False, compression="gzip")
back = pd.read_csv("export.dat", compression="gzip")
print(back)Reading needs the same hint. read_csv also infers from the extension, so export.dat would be read as plain text without compression="gzip" and fail or return garbage.
Passing options with a dictionary
To pass options to the compressor, give compression a dictionary. The method key is required. The other keys are forwarded to the underlying library.
import pandas as pd
df = pd.DataFrame({"a": range(1000), "b": ["text"] * 1000})
# Faster, slightly larger output, and byte-identical files on every run.
df.to_csv(
"fast.csv.gz",
index=False,
compression={"method": "gzip", "compresslevel": 1, "mtime": 1},
)
# Name the file inside a zip archive.
df.to_csv(
"orders.zip",
index=False,
compression={"method": "zip", "archive_name": "orders.csv"},
)Gzip stores a modification time in its header. Two runs on identical data therefore give files that differ by a few bytes, which breaks checksum comparisons. Fixing mtime makes the output reproducible.
A zip archive needs an inner file name. If you leave out archive_name, pandas derives one from the path, but naming it makes the archive easier to read later. read_csv can read a zip only when it holds exactly one file.
Trade-offs
Compression costs CPU time on every write and read. It also removes the ability to open the file in a text editor or to seek to a line without decompressing. Gzip and bz2 files cannot be appended to in the way a plain CSV can, although gzip does allow concatenated members. Treat each compressed file as a finished product.
For large, long-lived datasets, Parquet (covered later in this tutorial) compresses each column separately and keeps dtypes. A compressed CSV is the right choice when the reader needs CSV but the transfer size matters.
Encoding
Compression decides the file size. Encoding decides which bytes represent each character. Pandas writes text in UTF-8 by default, and that is the right choice unless you know the reader needs something else.
What breaks with the wrong encoding
If the writer and the reader disagree on the encoding, characters outside plain ASCII turn into nonsense. The name José can come out as José. If the encoding cannot represent a character at all, writing fails.
import pandas as pd
people = pd.DataFrame({"name": ["José", "Zoë", "Łukasz"], "score": [3, 5, 4]})
# Latin-1 covers Western European accents, but not "Ł".
try:
people.to_csv("people_latin1.csv", index=False, encoding="latin-1")
except UnicodeEncodeError as err:
print("Cannot encode:", err.reason)
# Replace what cannot be encoded with "?" instead of failing.
people.to_csv(
"people_latin1.csv",
index=False,
encoding="latin-1",
encoding_errors="replace",
)
print(pd.read_csv("people_latin1.csv", encoding="latin-1"))The encoding_errors argument takes the same values as Python's codec error handlers. The default is "strict", which raises an error. "replace" writes ? for each missing character. "ignore" drops it. Both silently lose data, so use them only when losing characters is acceptable, and say so in your documentation.
UTF-8 with a byte order mark
Excel on Windows often misreads a plain UTF-8 CSV when you open it by double-clicking. It guesses a legacy code page, and accented characters appear garbled. A byte order mark (BOM) is a short marker at the start of a file that signals UTF-8 to such programs. Pandas writes one when you choose utf-8-sig:
import pandas as pd
people = pd.DataFrame({"name": ["José", "Zoë", "Łukasz"], "score": [3, 5, 4]})
people.to_csv("people_bom.csv", index=False, encoding="utf-8-sig")
with open("people_bom.csv", "rb") as f:
print(f.read(3)) # b'\xef\xbb\xbf' is the BOM
# Reading with plain utf-8 keeps the BOM as part of the first column name.
print(pd.read_csv("people_bom.csv", encoding="utf-8").columns.tolist())
# Reading with utf-8-sig removes it.
print(pd.read_csv("people_bom.csv", encoding="utf-8-sig").columns.tolist())The second print shows '\ufeffname' as the first column, which breaks df["name"] lookups with a confusing KeyError. Use utf-8-sig on both sides, or use it on write only when the file is meant for Excel users.
Choosing an encoding
| Situation | Encoding |
|---|---|
| Files for programs, databases, other pandas code | `utf-8` (the default) |
| Files that people will open directly in Excel on Windows | `utf-8-sig` |
| A legacy system that documents a specific code page | That code page, for example `cp1252` or `latin-1` |
| Text in many scripts (Chinese, Arabic, mixed) | `utf-8`. Most legacy code pages cannot represent it. |
When someone else sends you a CSV, the file does not say which encoding it uses. If read_csv raises UnicodeDecodeError with the default, ask the sender, or try cp1252 or latin-1. Latin-1 never fails to decode, because every byte maps to a character, but it can give wrong characters without any error.
Combining compression and encoding
The two settings are independent. Pandas encodes the text first and then compresses the bytes, so you can set both in one call. When you read the file, pass the same pair back.
import pandas as pd
people = pd.DataFrame({"name": ["José", "Zoë", "Łukasz"], "score": [3, 5, 4]})
people.to_csv("people.csv.gz", index=False, encoding="utf-8-sig")
back = pd.read_csv("people.csv.gz", encoding="utf-8-sig")
print(back)If you pass an open file handle instead of a path, pandas uses the handle's own encoding and ignores the encoding argument for writing. Open the handle with the encoding you want, or pass the path and let pandas manage the file.
Common errors
- A
.gzfile that is not compressed. This happens when the extension is wrong or the method is not inferred. Check the first bytes: gzip starts with1f 8b. ImportErrorforzstandard. Writing.zstneedspip install zstandard. Gzip, bz2, xz, and zip need nothing extra.KeyErroron the first column after reading. The file has a BOM and you read it as plainutf-8. Useutf-8-sig.UnicodeEncodeErroron write. The chosen encoding cannot represent a character. Switch to UTF-8 unless a reader forces the legacy code page.- Garbled accents in Excel. The file is UTF-8 without a BOM. Write with
utf-8-sig, or import the file through Excel's data import dialog and select UTF-8.
Exercise
You write a report with df.to_csv("report.csv", encoding="utf-8-sig", compression="gzip") and then read it back with pd.read_csv("report.csv"). The call fails or returns unreadable data. Name the two problems and give the corrected read call.
Show answer
First, the file name ends in .csv, so read_csv infers no compression and tries to read gzip bytes as text. Second, the file starts with a byte order mark, so a plain utf-8 read would keep \ufeff in the first column name. The corrected call is pd.read_csv("report.csv", compression="gzip", encoding="utf-8-sig"). Better still, name the file report.csv.gz so both writing and reading infer gzip.
Exercise
A colleague on Windows says accented names look wrong when they double-click your UTF-8 CSV in Excel. A downstream Python job reads the same file with pd.read_csv(path) and indexes df["name"]. What encoding do you write with, and what must the Python job change?
Show answer
Write with encoding="utf-8-sig" so Excel recognises the file as UTF-8. The Python job must read with encoding="utf-8-sig", because the default utf-8 keeps the byte order mark in the first column name and df["name"] raises a KeyError.