Sub topic 3
Selecting Columns and Using PyArrow Scanners
Assume basic Python, table and column concepts, Parquet, and file paths. A scanner is a PyArrow object that reads a dataset in controlled pieces instead of loading everything at once.
Select Columns and Scan in Batches
Column selection, also called projection, limits the data read from each file. Filters can also prune partitions before reading file contents.
import pyarrow.dataset as ds
dataset = ds.dataset("sales", format="parquet", partitioning="hive")
scanner = dataset.scanner(
filter=(ds.field("year") == 2024),
columns=["country", "amount"],
batch_size=65_536,
)
total = 0.0
for batch in scanner.to_batches():
amounts = batch.column("amount").to_pylist()
total += sum(value for value in amounts if value is not None)
print(total)This scanner reads only the country and amount columns from matching partitions. to_batches() returns record batches, which are table fragments small enough to process incrementally.
dataset.to_table() is convenient for smaller results. Use a scanner when the result might exceed memory.
Tune Files and Row Groups
When writing, file size and row group size affect later scan performance. Row groups are independently readable groups of rows inside a Parquet file.
| Option | Purpose |
|---|---|
| `max_rows_per_file` | Limits rows in one output file |
| `max_rows_per_group` | Limits rows in one Parquet row group |
| `max_open_files` | Limits files open during writing |
For example:
ds.write_dataset(
table,
"sales_tuned",
format="parquet",
partitioning=["year"],
partitioning_flavor="hive",
max_rows_per_file=1_000_000,
min_rows_per_group=100_000,
max_rows_per_group=1_000_000,
existing_data_behavior="delete_matching",
)delete_matching replaces existing files in partitions touched by this write. Choose overwrite_or_ignore when existing files should remain and new file names should not collide.
Partition Keys, Remote Files, and Pitfalls
Choose columns commonly used for filtering, such as date or region. Avoid high-cardinality keys such as user IDs. Too many distinct values create many small files, which increases metadata and object-store overhead.
S3 works through a filesystem object:
import pyarrow.dataset as ds
import pyarrow.fs as fs
s3 = fs.S3FileSystem()
dataset = ds.dataset(
"my-bucket/sales",
filesystem=s3,
format="parquet",
partitioning="hive",
)Common errors include mismatched partition types, incorrect Hive paths, and accidentally scanning all columns. Inspect dataset.schema, dataset.files, and each fragment's partition_expression to debug discovery.
Exercise
What change usually reduces memory use when scanning a large dataset?
Show answer
Select only needed columns and process the scanner's record batches one at a time.