Sub topic 7
Reading and writing Parquet
This chapter assumes you know basic Python and pandas, and that you have seen Dask DataFrames, partitions, and lazy evaluation from earlier chapters. It covers how Dask stores data as Parquet, how to read only what you need, and the errors people hit most often.
Why Parquet suits Dask
Parquet is a columnar file format. It stores each column's values together instead of storing row after row, as CSV does. Three properties matter for Dask:
- Column selection. A reader can load only the columns you ask for and skip the rest on disk.
- Typed and compressed. Parquet records dtypes and compresses each column. You avoid the type guessing that CSV parsing needs, and files are smaller.
- Row groups and statistics. A file is split into row groups. Each row group stores min and max values per column, so a reader can skip groups that cannot match a filter.
CSV is row-oriented text. To read one column, a CSV reader still has to scan every byte and parse every field. For a Dask workflow that reads the same data many times, converting CSV to Parquet once usually pays off quickly.
Writing a Dask DataFrame to Parquet
to_parquet writes a directory. Each partition becomes its own file, and the writes run in parallel.
import pandas as pd
import dask.dataframe as dd
pdf = pd.DataFrame({
"zone": ["a", "b", "a", "b"],
"fare": [10.0, 20.0, 30.0, 40.0],
})
ddf = dd.from_pandas(pdf, npartitions=2)
ddf.to_parquet("out/fares.parquet")After this runs, out/fares.parquet is a directory, not a single file. It holds one file per partition, named like part.0.parquet and part.1.parquet. It may also hold a _metadata file, depending on your options and library versions.
Calling to_parquet is not lazy by default. It triggers computation immediately, because writing is the point of the call. If you want to build the write into a larger graph and run it later, pass compute=False. You then get a lazy object to compute yourself.
write_task = ddf.to_parquet("out/fares_lazy.parquet", compute=False)
write_task.compute()Useful write options
| Option | What it does |
|---|---|
| `engine` | Chooses the library that writes the files, usually `pyarrow`. |
| `compression` | Sets the codec, such as `snappy` (the common default), `gzip`, or `zstd`. |
| `partition_on` | Splits output into subdirectories by column values (Hive-style). |
| `write_index` | Whether to store the DataFrame index as a column. Default is `True`. |
| `overwrite` | Removes the existing directory before writing. Use it with care. |
| `write_metadata_file` | Controls whether a `_metadata` summary file is written. |
Check your installed Dask version's documentation for exact defaults, since they have changed between releases.
Reading Parquet and selecting columns
read_parquet is lazy. It reads the file footers to learn the schema and layout, then builds a graph. Data loads when you compute.
import dask.dataframe as dd
subset = dd.read_parquet("out/fares.parquet", columns=["zone", "fare"])
print(subset.npartitions)
print(subset.dtypes)Passing columns is the single most useful optimization on this page. With CSV, dropping columns after loading saves nothing at read time. With Parquet, unrequested columns are never read from disk.
You can pass either a directory, a single file, a list of files, or a glob pattern such as "data/*.parquet". Remote storage works with a URL such as s3://bucket/path/, provided the matching filesystem package (for example s3fs) is installed.
Filtering at read time
The filters argument lets the reader skip row groups using the stored statistics, before any data is loaded:
import dask.dataframe as dd
expensive = dd.read_parquet(
"out/fares.parquet",
columns=["zone", "fare"],
filters=[("fare", ">", 15.0)],
)
print(expensive.compute())Treat filters as a coarse pre-filter. It drops whole row groups that cannot match, but a row group that partly matches is still loaded, and non-matching rows inside it may remain. If you need exact results, apply the same condition again with a normal pandas-style filter:
expensive = expensive[expensive["fare"] > 15.0]Partitioned datasets with `partition_on`
If you often filter on a column with a small number of distinct values, you can store the data in one subdirectory per value.
import pandas as pd
import dask.dataframe as dd
pdf = pd.DataFrame({
"zone": ["a", "b", "a", "b"],
"fare": [10.0, 20.0, 30.0, 40.0],
})
ddf = dd.from_pandas(pdf, npartitions=2)
ddf.to_parquet("out/by_zone", partition_on=["zone"])The result looks like this:
out/by_zone/
zone=a/part.0.parquet
zone=b/part.0.parquetWhen you read this directory, Dask rebuilds the zone column from the directory names. A filter on zone then skips entire directories:
only_a = dd.read_parquet("out/by_zone", filters=[("zone", "==", "a")])
print(only_a.compute())Choose partition_on columns with few distinct values. A column with thousands of values creates thousands of tiny directories and files, which makes both writing and listing slow.
How files map to partitions
By default, Dask creates roughly one partition per Parquet file, or per row group when a file is large and the reader is configured to split them. So the number of partitions you read depends on how the data was written, not on your current needs.
This leads to two common situations:
- Many tiny files. Thousands of files of a few kilobytes each give thousands of tiny partitions. Scheduling overhead then dominates the useful work.
- A few huge files. A single large file may give too few partitions to use all your cores, or partitions too big to fit in a worker's memory.
Check npartitions right after reading. If it looks wrong, fix it either at read time (some versions accept options such as split_row_groups and blocksize to control how files are grouped or split) or afterwards with repartition, which a later chapter covers. Option names and defaults differ between Dask versions, so confirm them against your installed release.
Round trip: CSV to Parquet
A common first task is converting a large CSV dataset once, then working from Parquet afterwards.
import dask.dataframe as dd
raw = dd.read_csv("data/trips-*.csv", dtype={"zone": "string"})
raw.to_parquet("data/trips.parquet", compression="snappy")
trips = dd.read_parquet("data/trips.parquet", columns=["zone", "fare"])
print(trips.groupby("zone")["fare"].mean().compute())Setting dtypes explicitly when reading CSV matters here. Dask infers dtypes from a sample of the first file. If a column looks like integers in that sample but has missing values or text later, the read fails during computation. Parquet then stores whatever dtype you gave it, so fixing the types once at conversion time prevents the problem downstream.
Common errors and gotchas
- Index handling. By default,
to_parquetwrites the index andread_parquetrestores it. If your index is a default integer range per partition, you can end up with repeated index values across partitions. Passwrite_index=Falseif the index carries no meaning. - Overwriting a directory you are reading from. If you read from
out/dataand write back toout/datawithoverwrite=True, the directory can be deleted before the lazy read has loaded anything. Write to a new path instead. - Stale files. Writing a smaller dataset into an existing directory without removing it can leave old
part.N.parquetfiles from a previous run. A later read will include them. Use a fresh directory oroverwrite=Truedeliberately. - Mixed schemas. Files in one directory with different dtypes for the same column cause errors or silent upcasting on read. Keep the schema stable across writes.
- Object columns. Columns of Python objects with mixed types cannot be stored reliably. Convert them to
stringor a numeric type before writing. - Missing engine. Parquet needs
pyarrow(orfastparquet) installed. AnImportErrormentioning an engine means you need to install one.
Decision guide
| Situation | Suggested approach |
|---|---|
| Large CSV read repeatedly | Convert once to Parquet, then read from Parquet |
| Analysis uses a few columns | Pass `columns=[...]` to `read_parquet` |
| Queries often filter on a low-cardinality column | Write with `partition_on` and read with `filters` |
| Thousands of tiny output files | Repartition to larger partitions before writing |
| Data must be shared with non-Python tools | Parquet is widely supported by Spark, DuckDB, and others |
Exercise
You have a Dask DataFrame with 200 partitions and a column "country" with about 30 distinct values. Most of your queries filter on one country and use only two of the 25 columns. How would you write the data to Parquet, and how would you read it for a query on "NZ"?
Show answer
Write with ddf.to_parquet("out/data", partition_on=["country"]), which creates one subdirectory per country (30 in total, a reasonable number). Read with dd.read_parquet("out/data", columns=["col_a", "col_b"], filters=[("country", "==", "NZ")]). Dask then skips every other country's directory and reads only the two needed columns. Check npartitions afterwards, because each country directory may hold many small files if the DataFrame was split into 200 partitions. Repartition before writing if the files come out too small.
Exercise
A teammate runs ddf.to_parquet("out/data", overwrite=True) where ddf = dd.read_parquet("out/data"). What goes wrong, and what is the fix?
Show answer
The overwrite deletes the out/data directory before the lazy read has loaded its partitions, so the source files are gone or the read fails. The fix is to write to a different path, such as out/data_v2, and then rename or switch paths once the write has finished.