Sub topic 11
Parquet compression and partitioned datasets
This chapter assumes you can already write a single file with df.to_parquet(...), and that you have pyarrow installed. It covers two things. The first is how to choose a compression codec. The second is how to split one large DataFrame into a directory of files with partition_cols, and how to read that directory back.
How Parquet compression works
Parquet compresses each column chunk separately inside the file, not the file as a whole. Every column is compressed on its own, and the footer metadata records which codec was used. Two consequences follow:
- You choose the codec only when writing.
read_parquetdetects it and decompresses without extra arguments. - Readers can still skip columns they do not need, because the other columns do not have to be decompressed.
Parquet also encodes values before compression, for example with dictionary encoding for repeated strings. A Parquet file is therefore usually much smaller than the same data as CSV, even with no codec.
The compression argument of to_parquet takes these values:
| Value | Typical behavior |
|---|---|
| `"snappy"` | The default. Fast to write and read, moderate size reduction. |
| `"zstd"` | Better ratio than snappy at similar speed. A good general choice for new files. |
| `"gzip"` | Good ratio, slower to write and read. Supported almost everywhere. |
| `"brotli"` | Often the smallest output, but slow to write. |
| `"lz4"` | Very fast, with a ratio similar to or a little worse than snappy. |
| `None` | No compression. Useful when the storage layer already compresses. |
Which codecs are available depends on the engine and how it was built. If a codec is missing, the write raises an error. The pyarrow wheels from pip include all the codecs in the table.
Comparing codecs on your own data
Ratios depend heavily on the data: repeated strings compress very well, random floats do not. Measure on a sample of your real data before choosing. This script writes the same DataFrame with each codec and prints the file sizes.
import os
import numpy as np
import pandas as pd
rng = np.random.default_rng(42)
n = 200_000
df = pd.DataFrame({
"country": rng.choice(["DE", "FR", "ES", "IT"], size=n),
"status": rng.choice(["paid", "pending", "refunded"], size=n),
"amount": rng.normal(50, 15, size=n).round(2),
})
for codec in [None, "snappy", "gzip", "zstd", "brotli"]:
path = f"orders_{codec}.parquet"
df.to_parquet(path, index=False, compression=codec)
size_kib = os.path.getsize(path) / 1024
print(f"{str(codec):>7}: {size_kib:,.0f} KiB")Add a timing call around each to_parquet if write speed matters to you. For data you write once and read many times, a slower codec with a better ratio often pays off. For a pipeline that rewrites data every few minutes, a fast codec is usually the better choice.
Extra keyword arguments to to_parquet are passed on to the engine. With pyarrow you can therefore tune a codec's level:
df.to_parquet(
"orders_zstd9.parquet",
index=False,
compression="zstd",
compression_level=9,
)Higher levels give smaller files and slower writes. The valid range depends on the codec, so check the codec's documentation before going beyond the defaults.
Why partition a dataset
A single Parquet file is fine up to a few gigabytes. A partitioned dataset is a directory of files, organized by the values of one or more columns. It helps in three situations:
- Queries usually filter on one column, such as a date or a country. The reader can skip entire directories that cannot match.
- Several processes need to write different slices without touching the same file.
- A single output file would be too large to handle comfortably.
The cost is more files and more directories to manage. Choose partitioning deliberately. Do not apply it by default.
Writing a partitioned dataset
Pass the column names to partition_cols. Partitioning needs the pyarrow engine, so name it explicitly:
df.to_parquet(
"sales_by_country",
engine="pyarrow",
compression="zstd",
partition_cols=["country"],
index=False,
)The path is now a directory, not a file. List what was written:
import os
for root, _, files in sorted(os.walk("sales_by_country")):
for name in sorted(files):
print(os.path.join(root, name))You will see one subdirectory per distinct value, named country=DE, country=ES, and so on, each holding one or more .parquet files with generated names. The layout looks like this:
The directory name is where the partition value is stored. The files inside do not contain the country column. This is why partitioned output is smaller, and why you must read the whole directory and not a single inner file if you want that column back.
Partitioning on several columns
Pass more than one column to get nested directories. The order sets the nesting:
df.to_parquet(
"sales_nested",
engine="pyarrow",
partition_cols=["country", "status"],
index=False,
)This produces paths such as sales_nested/country=DE/status=paid/.... The first column should be the one you filter on most often.
Reading a partitioned dataset
Give read_parquet the directory path. The partition column is rebuilt from the directory names:
full = pd.read_parquet("sales_by_country")
print(full.dtypes)
print(full["country"].head())Two details matter here:
- The partition column comes back with the
categorydtype, not as plain strings. Its original dtype is not stored, because only the directory name is. Convert it withastype("string")orastype(int)if you need to. - Row order is not guaranteed to match the original. Files are read directory by directory. Sort explicitly if order matters.
Reading only part of the data
The benefit of partitioning appears when you filter. With the pyarrow engine, filters skips directories that cannot match:
germany = pd.read_parquet(
"sales_by_country",
filters=[("country", "==", "DE")],
)
print(len(germany))You can combine this with columns to also skip columns:
subset = pd.read_parquet(
"sales_by_country",
columns=["amount"],
filters=[("country", "in", ["DE", "FR"])],
)Filters on ordinary columns, not partition columns, are applied using statistics stored in each file, so they can still skip row groups. They do not remove every non-matching row. Apply a normal pandas filter afterward if you need an exact result.
Choosing partition columns
Good partition columns have these properties:
- They have a modest number of distinct values, from a handful up to a few hundred.
- They match how readers filter. Dates (a year or month column), regions, and tenant IDs are common.
- Each partition holds enough data to fill a reasonably sized file. Aim for tens of megabytes at the very least.
Avoid columns with high cardinality, such as order_id or a timestamp with seconds. A column with a million distinct values creates a million directories. This is the small files problem. Listing, opening, and reading that many tiny files can be far slower than reading one large file, and the metadata overhead can exceed the data itself.
If your natural key is too fine, derive a coarser column first:
orders = pd.DataFrame({
"ordered_at": pd.to_datetime(["2026-01-05", "2026-01-20", "2026-02-03"]),
"amount": [19.99, 5.5, 12.0],
})
orders["month"] = orders["ordered_at"].dt.strftime("%Y-%m")
orders.to_parquet(
"orders_by_month",
engine="pyarrow",
partition_cols=["month"],
index=False,
)Common errors
- Partition column missing after reading one inner file. The column exists only in the directory name. Read the dataset's root directory.
ImportErroror an unsupported engine message withpartition_cols. Installpyarrowand passengine="pyarrow".- Unexpected
categorydtype. This is how partition columns are restored. Cast to the dtype you need after reading. - Missing values in partition columns. Rows with a missing partition value are written into a directory named with a placeholder such as
__HIVE_DEFAULT_PARTITION__. Fill or drop missing values first, so the directory names are meaningful. - Many tiny files. Reduce the number of partition columns or coarsen them, for instance month instead of day.
Verifying a partitioned write
Reading back and comparing works as for single files, with two adjustments. The partition column comes back as category, and the row order may differ. Normalize both before comparing:
restored = pd.read_parquet("sales_by_country")
restored["country"] = restored["country"].astype(df["country"].dtype)
key = ["country", "status", "amount"]
left = df.sort_values(key).reset_index(drop=True)
right = restored[df.columns].sort_values(key).reset_index(drop=True)
pd.testing.assert_frame_equal(left, right)If this raises no error, the row count, values, and dtypes all match.
Exercise
You write a DataFrame with df.to_parquet("out", engine="pyarrow", partition_cols=["order_id"]), where order_id has about 500,000 distinct values. Reading it back is much slower than reading a single file. What is the cause, and what two changes would you make? Also, what dtype will a partition column have after read_parquet("out")?
Show answer
The cause is the small files problem. Partitioning on a high-cardinality column creates about 500,000 directories, each with a tiny file, so listing and opening them dominates the read time. Fix it by partitioning on a coarser column instead, such as a derived month or region, and by writing without partitioning if readers rarely filter by that column. A partition column comes back with the category dtype, and you can cast it with astype to the original type.