Sub topic 11
Selecting columns and using scanners
This chapter assumes you can write and open a Hive-partitioned Parquet dataset with ds.write_dataset and ds.dataset. It also assumes you can build filter expressions with ds.field. Here you will control which columns are read, and you will use a scanner to decide how the data is delivered.
Why column selection matters
Parquet stores each column as a separate column chunk inside every row group. If you ask for two columns out of twenty, PyArrow can skip the other eighteen chunks without reading them. A wide table with a narrow query can read a small fraction of the bytes.
Partition columns work differently. Their values come from directory names, not from file contents. Selecting year or country costs no extra reads from the Parquet data.
Projection with `to_table`
The shortest way to project is the columns argument of Dataset.to_table. The example below builds a small dataset first, so it runs as shown.
import pyarrow as pa
import pyarrow.dataset as ds
table = pa.table({
"year": [2023, 2023, 2024, 2024],
"country": ["DE", "FR", "DE", "FR"],
"amount": [10.5, 20.0, 7.25, 3.0],
})
part = ds.partitioning(
pa.schema([("year", pa.int64()), ("country", pa.string())]),
flavor="hive",
)
ds.write_dataset(
table,
"sales",
format="parquet",
partitioning=part,
existing_data_behavior="overwrite_or_ignore",
)
dataset = ds.dataset("sales", format="parquet", partitioning=part)
result = dataset.to_table(columns=["country", "amount"])
print(result.schema)The result has only the two requested columns, in the order you listed them. Asking for a column that does not exist in the dataset schema raises an error.
What a scanner is
to_table is a shortcut. Underneath, PyArrow builds a Scanner, an object that holds a scan plan: which dataset, which filter, which columns, and how to read. Creating one reads no data. You create it with dataset.scanner(...) or ds.Scanner.from_dataset(...), and the work happens when you call a method such as to_table.
scanner = dataset.scanner(
columns=["country", "amount"],
filter=ds.field("year") == 2024,
)
print(scanner.projected_schema)
print(scanner.dataset_schema)
print(scanner.count_rows())
print(scanner.head(1).to_pydict())
print(scanner.to_table().to_pydict())projected_schemais the schema of the output after projection.dataset_schemais the full schema.count_rows()applies the filter and returns the number of matching rows. For many datasets it can answer from file metadata and avoid reading column data.head(n)returns the firstnrows as a table and stops scanning early.to_table()reads everything that matches into memory.
A scanner built from a dataset can be consumed more than once. A scanner built from a one-shot source, such as ds.Scanner.from_batches, can be consumed only once.
Filter columns do not have to be projected
The filter and the projection are independent. You can filter on year and leave it out of the output.
scanner = dataset.scanner(
columns=["amount"],
filter=(ds.field("country") == "DE") & (ds.field("year") >= 2023),
)
print(scanner.to_table().to_pydict())Both filter terms here are on partition columns, so PyArrow can skip whole directories. If the filter used a data column such as amount, the scanner would still read that column to evaluate the filter, even though it is not in the output. It would then drop it from the result.
Computed columns
The columns argument also accepts a dictionary that maps output names to expressions. This lets you derive columns inside the scan, and it avoids a separate pass over the table.
scanner = dataset.scanner(
columns={
"country": ds.field("country"),
"amount_cents": ds.field("amount") * 100,
},
filter=ds.field("year") == 2023,
)
print(scanner.to_table().to_pydict())With a dictionary, every output column must be listed explicitly, including the ones you only want to pass through. Expressions support arithmetic, comparisons, and a set of compute functions. For logic they cannot express, project the raw columns and use pyarrow.compute afterwards.
How a scan flows
The scanner prunes fragments using the filter and the partition expressions, reads only the projected and filter columns from the surviving files, and then applies the filter to the rows.
Choosing how to consume results
A scanner offers several ways to get data out. Pick based on how much memory you can spend and what you need to know about each piece.
| Method | Returns | Use when |
|---|---|---|
| `to_table()` | One `Table` | The result fits in memory |
| `to_batches()` | Iterator of `RecordBatch` | You process data incrementally |
| `to_reader()` | `RecordBatchReader` | You pass a stream to another API, such as a writer |
| `scan_batches()` | Iterator of tagged batches | You need to know which fragment a batch came from |
| `head(n)` | One `Table` | You want a quick sample |
| `count_rows()` | An integer | You only need a count |
scan_batches() yields objects that carry both the batch and its source fragment.
scanner = dataset.scanner(columns=["amount"])
for tagged in scanner.scan_batches():
print(tagged.fragment.path, tagged.record_batch.num_rows)This is a useful debugging tool when a result looks wrong and you want to find the file responsible.
Streaming an aggregate
When the dataset is larger than memory, aggregate batch by batch and keep only a small running state.
import pyarrow.compute as pc
scanner = dataset.scanner(
columns=["amount"],
filter=ds.field("year") >= 2023,
batch_size=64_000,
)
total = 0.0
rows = 0
for batch in scanner.to_batches():
total += pc.sum(batch.column("amount")).as_py() or 0.0
rows += batch.num_rows
print(total, rows)pc.sum returns a null scalar when a batch has no non-null values, so as_py() gives None. The or 0.0 handles that case. The computation uses Arrow's compute kernels instead of looping over Python values, which is much faster than to_pylist() for large batches.
Tuning the scan
The scanner exposes a few parameters that trade memory for throughput.
batch_sizeis the maximum number of rows in each record batch. The default is about 131,000 rows. Lower it when rows are wide and memory is tight.batch_readaheadandfragment_readaheadcontrol how many batches and files are read ahead of the consumer. Higher values keep the CPU or network busy but hold more data in memory.use_threadsdefaults toTrue. Set it toFalsewhen you need deterministic behavior while debugging, or when you are already parallelizing outside PyArrow.
Common mistakes
- Reading all columns by default.
dataset.to_table()with nocolumnsreads everything. On wide data this is the most common source of slow scans and high memory use. - Calling
to_table()on a huge result. Useto_batches()orto_reader()when the filtered result may not fit in memory. - Forgetting the dictionary form needs every column. If you pass a dictionary and leave out
country, it is not in the output. - Reusing a one-shot scanner. A scanner made from a batch iterator or reader is consumed after one pass. A second pass returns nothing or raises an error.
- Expecting
head()to be random. It returns the first rows the scan produces, which depend on file order and threading.
Exercise
A dataset is partitioned by year and country and has data columns amount, customer_id and notes. You want the sum of amount for country == "DE", and the full result is far larger than memory. Which scanner call and arguments would you use, and which columns will actually be read from the data files?
Show answer
Create dataset.scanner(columns=["amount"], filter=ds.field("country") == "DE") and loop over scanner.to_batches(), adding pc.sum(batch.column("amount")).as_py() or 0.0 to a running total. Only the amount column chunks are read from the files in country=DE directories. country comes from the paths, and customer_id and notes are never read. Streaming batches keeps memory use bounded by the batch size.