skip to content

A nightly pandas job writes Parquet with to_parquet(partition_cols=['run_date']): how do you read one week of three columns with read_parquet?

level: seniorimportance: should knowfreq 45%

answer

  1. prune before you load
  2. one argument per axis
  3. list of (column, op, value) tuples
  4. directories skipped by name
  5. engine decides row-level filtering

basics

~10 s

Call read_parquet on the dataset directory with columns= naming the three columns and filters=[('run_date', 'in', week)]: unread columns are never decoded, other days' directories are skipped, and the pyarrow engine also drops non-matching rows.

solid answer

~40 s

`to_parquet(root, partition_cols=['run_date'])` writes one subdirectory per value, like `run_date=2026-10-03/`. To read a week I call `pd.read_parquet(root, columns=['run_date', 'store_id', 'revenue'], filters=[('run_date', 'in', week)])`. `columns` means only those columns are decoded; `filters` is a list of `(column, op, value)` tuples, ANDed inside a list and ORed across an outer list, and it lets the reader skip whole partition directories and row groups. With the `pyarrow` engine, which `engine='auto'` picks when PyArrow is installed, the filter is also applied row by row; with `fastparquet` it works only at partition and row-group level, so I filter again in pandas. The partition column is rebuilt from directory names, typically as `category`, so I check `dtypes` before joining on it.

code

python · 23 lines
python
import tempfile

import pandas as pd

df = pd.DataFrame({
    "run_date": ["2026-10-01", "2026-10-01", "2026-10-02", "2026-10-08"],
    "store_id": [1, 2, 1, 1],
    "revenue": [120.0, 80.5, 99.0, 150.0],
    "basket_size": [3, 2, 4, 5],
})

with tempfile.TemporaryDirectory() as root:
    df.to_parquet(root, engine="pyarrow", partition_cols=["run_date"], index=False)

    week = [f"2026-10-0{d}" for d in range(1, 8)]
    out = pd.read_parquet(
        root,
        engine="pyarrow",
        columns=["run_date", "store_id", "revenue"],
        filters=[("run_date", "in", week)],
    )
    print(len(out))  # 3: the 2026-10-08 partition is never read
    print(out.dtypes)  # check run_date: rebuilt from directory names

go deeper

for a junior

Recall that read_parquet takes columns= to read only some columns and that a partitioned dataset is a directory you can pass as the path.

for a middle

Explain the filters tuple syntax, AND inside a list and OR across lists, and why it skips directories before any data is decoded.

for a senior

Show you know the engine changes the guarantee: pyarrow filters rows, fastparquet only partitions and row groups. Mention the category partition column and the rerun-duplicates trap.

for a principal

Weigh partitioning by run_date against how readers actually slice the data, and pin engine and index settings in the writer so every consumer sees the same columns.

## What the nightly job writes `DataFrame.to_parquet(path, engine='auto', compression='snappy', index=None, partition_cols=None)` writes a DataFrame in the **Parquet** format, a binary columnar file. With `partition_cols=['run_date']`, a directory path and the pyarrow engine, pandas hands the frame to PyArrow's dataset writer, and the result is a **hive-style directory tree**: one subdirectory per distinct value (`run_date=2026-10-03/`), each holding one or more Parquet files for the rows with that value. The arguments that matter for a nightly job: - **`path`** must be a string (a directory) when `partition_cols` is set; the docstring says `partition_cols` must be `None` otherwise. - **`index=None`** (the default) stores a default `RangeIndex` as metadata only, while any other index is written as one or more columns (`__index_level_0__` with the pyarrow engine). Pass `index=False`, or `reset_index()` first, so readers in other tools do not meet an unexpected column. - **`compression`** defaults to `'snappy'`; `'zstd'`, `'gzip'`, `'brotli'`, `'lz4'` and `None` are the other choices. - **`engine`** is `'auto'`, `'pyarrow'` or `'fastparquet'`. How row groups, encodings and statistics are laid out inside each file is the Parquet format's own subject; here the point is which pandas arguments let a reader avoid that work. ## Reading a slice: `columns` and `filters` `pd.read_parquet(path, engine='auto', columns=None, ..., filters=None)` accepts the dataset directory as well as a single file. Two arguments narrow the read before any data reaches pandas: | argument | narrows | work avoided | |---|---|---| | `columns=[...]` | which columns | the other columns are never decoded | | `filters=[...]` | which partitions and row groups (and rows, with pyarrow) | whole directories and row groups are skipped | ```python week = [f"2026-10-0{d}" for d in range(1, 8)] sales = pd.read_parquet( "warehouse/daily_sales", columns=["run_date", "store_id", "revenue"], filters=[("run_date", "in", week)], ) ``` Filtering in pandas after a full `read_parquet` gives the same rows, but only after every day of history has been read and decoded; the arguments move the selection into the reader. ## The `filters` syntax - A filter is a tuple **`(column, op, value)`**, where `op` is one of `==`, `=`, `>`, `>=`, `<`, `<=`, `!=`, `in`, `not in`. - Tuples in one inner list are combined with **AND**; inner lists inside an outer list are combined with **OR**: `[[("run_date", "==", "2026-10-03"), ("store_id", "==", 7)], [("run_date", "==", "2026-10-04")]]`. - A single flat list of tuples means AND only. - The value must compare with the column as the dataset types it. A partition column is typed from its directory names, so a date written as text is compared as text; ISO dates in a list for `in` sidestep ordering questions. ## The engine decides how far a filter goes `engine='auto'` reads the `io.parquet.engine` option, and when that is also `'auto'` it tries **pyarrow** first and falls back to **fastparquet**. The docstring is explicit about the difference: 1. With `engine="pyarrow"` the filter skips partitions and row groups **and** is applied row by row, so every returned row satisfies it. 2. With other engines, filtering happens only at the partition and row-group level: a row group whose statistics overlap the predicate is read whole, so rows that fail the filter can still come back. Filter again in pandas afterwards. `dtype_backend='pyarrow'` or `'numpy_nullable'` on `read_parquet` is likewise not supported with fastparquet, which is one more reason teams pin `engine="pyarrow"` rather than rely on `'auto'`. ## What comes back - The **partition column** is rebuilt from the directory names rather than from the file contents. With the pyarrow engine it typically comes back as a `category` dtype, and it may sit after the file's own columns. Check `dtypes` before merging on it, and cast with `astype` if a join key needs another dtype. - The **index** is a fresh `RangeIndex` unless a non-range index was written as a column. - **Row order** across partitions is whatever the reader produced; sort explicitly if the next step depends on order. ## Pitfalls interviewers probe 1. Reading the whole dataset and then masking it, which defeats the partition layout entirely. 2. Expecting exact row-level filtering on a non-partition column under fastparquet. 3. Rerunning a day: the dataset writer generates new file names per write, so a rerun can add files beside the old ones and the day is read twice. Clear that partition directory before rewriting it. 4. Leaving `index=None` on a frame with a non-range index and shipping an extra column to every consumer.

  • What happens when the nightly job is rerun for a day that already has a partition directory?
    With `partition_cols`, pandas passes the write to PyArrow's dataset writer, which generates new file names per write. A rerun can therefore add files beside yesterday's instead of replacing them, and `read_parquet` then returns that day twice. Delete or rewrite the `run_date=...` directory before writing the day again, or write to a fresh location and swap it in.
  • Why might filters on a revenue column still return rows below the threshold?
    Without the pyarrow engine, `filters` only skips partitions and row groups whose statistics rule the predicate out. A row group that holds both high and low revenue values is read whole, so failing rows come back. Pin `engine='pyarrow'` for row-wise filtering, or apply a boolean mask after reading.

A filing cabinet with one drawer per day: filters tells you which drawers to open, columns tells you which folders to pull from each open drawer, and the pyarrow engine also leafs through each folder to drop the pages that do not match.

  • Reads the whole dataset with read_parquet and filters it afterwards with a boolean mask
  • Believes filters always removes every non-matching row, whatever the engine
  • Expects the partition column to come back with exactly the dtype it had before writing
  • Thinks columns= only hides columns after the full file has been decoded
  • Assumes rerunning to_parquet with partition_cols replaces that day's files