Sub topic 12
Scanning datasets with filters and column projection
This chapter assumes you can run pyarrow code, that you know what Parquet files are, and that you have read the chapters on tables, schemas and compute functions. It covers how pyarrow.dataset reads many files as one logical table, and how to ask for only the rows and columns you need.
Why a dataset is not a table
A pa.Table lives in memory. Real data often sits in dozens or thousands of files on disk or in object storage. Loading all of it just to keep a few columns wastes memory and I/O.
A pyarrow.dataset.Dataset is a lazy description of such data. Creating one reads file listings and (usually) one file's schema. It does not load the values. You get data only when you run a scan.
A scan accepts two instructions:
- Projection picks which columns to return.
- Filter keeps only the rows that match a condition.
Both are passed to the reader, so the reader can skip work instead of discarding results afterward.
Build a small partitioned dataset
The examples below need files on disk. This code writes six rows into Hive-style folders, one per year.
import pyarrow as pa
import pyarrow.dataset as ds
table = pa.table({
"id": [1, 2, 3, 4, 5, 6],
"name": ["a", "b", "c", "d", "e", "f"],
"year": [2023, 2023, 2024, 2024, 2025, 2025],
})
ds.write_dataset(
table,
"data",
format="parquet",
partitioning=ds.partitioning(pa.schema([("year", pa.int64())]), flavor="hive"),
existing_data_behavior="overwrite_or_ignore",
)This creates folders such as data/year=2023/ and data/year=2024/, each holding a Parquet file. The year values are stored in the folder names, not inside the files.
Open the dataset
import pyarrow.dataset as ds
dataset = ds.dataset("data", format="parquet", partitioning="hive")
print(dataset.schema)
print([f.path for f in dataset.get_fragments()])The partitioning="hive" argument tells Arrow to read year=2023 as a column named year. Without it, the folder names are ignored and year is missing from the schema. Arrow infers the partition column type from the folder names, so year becomes int32 here. If you need a specific type, pass ds.partitioning(schema, flavor="hive") as in the write step.
A fragment is one unit of the dataset, normally one file. Scans work fragment by fragment, which is what makes skipping possible.
Filter and project in one scan
This is the pattern from the topic plan, applied to the dataset above.
import pyarrow.dataset as ds
dataset = ds.dataset("data", format="parquet", partitioning="hive")
table = dataset.to_table(
columns=["id", "name"],
filter=ds.field("id") > 1,
)
print(table.num_rows)
print(table.column_names)The result has 5 rows and the columns id and name. The columns list is the projection. The filter argument takes an expression, which is a description of a condition and not a computed result. ds.field("id") > 1 does not compare any data. It builds an object that the scan evaluates later.
Building filter expressions
Combine conditions with & (and), | (or) and ~ (not). Wrap each comparison in parentheses because of Python operator precedence.
import pyarrow.dataset as ds
dataset = ds.dataset("data", format="parquet", partitioning="hive")
recent_and_large = (ds.field("year") >= 2024) & (ds.field("id") > 3)
in_set = ds.field("year").isin([2023, 2025])
has_name = ds.field("name").is_valid()
print(dataset.to_table(filter=recent_and_large).num_rows)
print(dataset.to_table(filter=in_set).num_rows)
print(dataset.to_table(filter=has_name).num_rows)These print 3, 4 and 6. Useful expression methods include isin(), is_valid() and is_null().
Rows where the filter evaluates to null are dropped, not kept. If name is null and you filter on ds.field("name") == "a", the comparison gives null for that row, so the row is excluded. Use is_null() explicitly when you want null rows.
How a scan skips work
The filter does more than discard rows at the end. The reader uses it at several levels, as shown below.
- Partition pruning. With a filter such as
ds.field("year") == 2024, Arrow never opens theyear=2023oryear=2025files. This works because the partition values are known from paths. - Row group statistics. Parquet files store the minimum and maximum of each column per row group (a block of rows). If a row group's maximum
idis 3 and you filterid > 10, that row group is skipped without being read. - Column selection. Parquet is columnar on disk, so unprojected columns are never read. Columns used only by the filter are still read, but they are not returned.
- Row filtering. Rows that survive the first three steps are tested individually.
Steps 1 to 3 are optimizations. They never change the result. The row-level filter in step 4 always makes the answer exact.
For non-Parquet formats such as CSV, steps 2 and 3 do not apply in the same way. CSV has no statistics and no column-wise layout, so the file must still be parsed. Partition pruning still works.
Using a Scanner
dataset.to_table(...) is shorthand. The underlying object is a Scanner, which you can create once and use in several ways.
import pyarrow.dataset as ds
dataset = ds.dataset("data", format="parquet", partitioning="hive")
scanner = dataset.scanner(
columns=["id", "year"],
filter=ds.field("year") == 2024,
)
print(scanner.count_rows())
for batch in scanner.to_batches():
print(batch.num_rows, batch.schema.names)to_batches() yields record batches one at a time. You can process a dataset much larger than memory this way, keeping only one batch alive at a time. Use to_table() only when the filtered result fits in memory.
count_rows() can often answer from metadata and the filter, without materializing the columns. dataset.head(n) returns the first n rows, which is useful for a quick look.
Computed columns in a projection
The columns argument can also be a dictionary that maps new names to expressions.
import pyarrow.dataset as ds
dataset = ds.dataset("data", format="parquet", partitioning="hive")
table = dataset.to_table(
columns={
"id": ds.field("id"),
"next_id": ds.field("id") + 1,
},
filter=ds.field("year") == 2025,
)
print(table.to_pydict())The output is {'id': [5, 6], 'next_id': [6, 7]}. The expression runs inside the scan with the same vectorized compute functions you can call from pyarrow.compute.
Common errors
| Symptom | Cause | Fix | Column |
|---|---|---|---|
| `ValueError` about truth value of an expression | Used `and`, `or` or `not` | Use `&`, `\ | ` and `~` with parentheses |
| `ArrowInvalid` about a missing field | Column name typo, or partition column not discovered | Check `dataset.schema`, and pass `partitioning="hive"` | |
| Filter returns no rows | Compared a string column to a number, or types differ after inference | Compare against a value of the column's type; check `dataset.schema` | |
| Memory error on large data | Called `to_table()` on a result that is too big | Use `to_batches()` and process incrementally, or tighten the filter | |
| Partition column has an unexpected type | Arrow inferred `int32` from folder names | Pass an explicit partitioning schema |
What a scan does not do
A dataset scan reads and filters. It is not a query engine. It has no joins, no grouped aggregation and no sorting of its own. After the scan, pass the resulting table or batches to compute functions, or to an engine that consumes Arrow data, to do those steps. The scan's job is to hand over as little data as possible.
Exercise
A dataset is partitioned by year in Hive-style folders and stored as Parquet. You run dataset.to_table(columns=["name"], filter=(ds.field("year") == 2024) & (ds.field("id") > 3)). Which columns does the reader need to load from the Parquet files in the year=2024 folder, which folders can it skip entirely, and why is the id column read even though it is not in columns?
Show answer
The reader loads name and id from the year=2024 folder. name is projected, and id is needed to evaluate the filter. The year=2023 and year=2025 folders are skipped by partition pruning, because their paths show that year cannot equal 2024. The year column is not read from the files at all, since its value comes from the folder name. id is not returned in the result, because it is not in columns, but the filter must still read it. Row group statistics on id may also let the reader skip row groups whose maximum id is 3 or less.
Exercise
Why does ds.field("id") > 1 and ds.field("year") == 2024 fail, and how do you write it correctly?
Show answer
Python's and tries to convert an expression to a single True or False value, which an Arrow expression cannot give because it describes a condition and has not been computed. Use the & operator with parentheses around each comparison: (ds.field("id") > 1) & (ds.field("year") == 2024).