Sub topic 9
Inspecting row groups and statistics with PyArrow
Parquet stores its description of itself in the file footer. Reading the footer shows how a file is split into row groups, how well each column compressed, and which value ranges each row group holds. This chapter shows how to read that information with PyArrow and what to look for.
This chapter assumes you can run Python with pyarrow installed. It also assumes you know the layout of a Parquet file (row groups contain column chunks, and column chunks contain pages) and the idea of min/max statistics.
What the metadata gives you
The metadata is a tree. PyArrow exposes each level as an object:
Each access such as md.row_group(0) or rg.column(0) reads from metadata already parsed in memory. Opening a file with pq.ParquetFile reads only the footer, not the data pages. You can inspect a multi-gigabyte file in milliseconds, and on object storage this costs a few small range requests.
Create a file to inspect
This script writes one million rows as ten row groups of 100,000 rows, compressed with Zstandard. The later examples reuse this file.
import pyarrow as pa
import pyarrow.parquet as pq
table = pa.table({
"id": list(range(1_000_000)),
"category": ["a", "b", "c", "d"] * 250_000,
})
pq.write_table(
table,
"events.parquet",
row_group_size=100_000,
compression="zstd",
)File-level metadata
pq.ParquetFile opens the file. Its metadata attribute is a FileMetaData object. The function pq.read_metadata("events.parquet") returns the same object without keeping a file handle.
import pyarrow.parquet as pq
pf = pq.ParquetFile("events.parquet")
md = pf.metadata
print(md.num_rows, md.num_row_groups, md.num_columns)
print(md.created_by)
print(md.format_version)
print(pf.schema_arrow)For this file, num_rows is 1000000, num_row_groups is 10, and num_columns is 2. The created_by string names the writer library and version. It helps when you debug a file produced by Spark, DuckDB, or another tool, because writers differ in defaults and in how they fill statistics.
pf.schema_arrow is the schema as Arrow types. pf.schema is the lower-level Parquet schema with physical types and, for nested data, definition and repetition levels.
Row group metadata
md.row_group(i) returns a RowGroupMetaData with these attributes:
num_rows: the number of rows in the group.num_columns: the number of column chunks.total_byte_size: the uncompressed size of the group's data.
The row counts should match what you asked the writer for. The last group is usually smaller because it holds the remainder. If you see thousands of tiny groups, the writer flushed too often, which is a common cause of slow reads. Chapter 11 covers how to pick a size.
Column chunk metadata and statistics
rg.column(j) returns a ColumnChunkMetaData. The attributes you will use most are these:
| Attribute | Meaning |
|---|---|
| `path_in_schema` | Column name. Nested columns appear as dotted paths. |
| `compression` | Codec used for the pages, such as `ZSTD`. |
| `encodings` | Encodings used in the chunk. Exact names vary by writer and version. |
| `total_compressed_size` | Bytes on disk for this chunk. |
| `total_uncompressed_size` | Bytes after decompression, before decoding. |
| `num_values` | Number of values, including nulls. |
| `statistics` | A `Statistics` object, or `None`. |
col.statistics carries min, max, null_count, and the flags has_min_max and has_null_count. PyArrow converts min and max to Python values, so a string column gives str and an integer column gives int.
Here is the loop that walks the whole tree and prints one line per column chunk:
import pyarrow.parquet as pq
md = pq.ParquetFile("events.parquet").metadata
print("rg column rows min max nulls compressed ratio")
for i in range(md.num_row_groups):
rg = md.row_group(i)
for j in range(rg.num_columns):
col = rg.column(j)
st = col.statistics
if st is not None and st.has_min_max:
lo, hi = st.min, st.max
else:
lo = hi = None
nulls = st.null_count if st is not None and st.has_null_count else None
ratio = col.total_uncompressed_size / col.total_compressed_size
print(
f"{i:<3} {col.path_in_schema:<10} {rg.num_rows:<7} "
f"{lo!s:<7} {hi!s:<7} {nulls!s:<6} "
f"{col.total_compressed_size:<11} {ratio:.1f}"
)The output shows two patterns:
- The
idcolumn has disjoint ranges. Row group 0 holds 0 to 99999, row group 1 holds 100000 to 199999, and so on. Each group covers a narrow slice of the value space. - The
categorycolumn reportsaas min anddas max in every row group. Its values cycle through the same four letters everywhere, so the ranges overlap completely.
The first pattern is what skipping needs. The second is why statistics cannot help a filter on category. Whether statistics help depends on how your data is ordered when written, not only on whether statistics exist.
The ratio column also differs. category has four distinct values, so dictionary encoding and compression shrink it heavily. id is nearly all distinct, so its ratio is lower.
Simulating row group skipping
Query engines use these statistics to decide which row groups to read. You can reproduce that decision in a few lines. This function returns the row groups that could contain an id at or above a threshold:
import pyarrow.parquet as pq
pf = pq.ParquetFile("events.parquet")
md = pf.metadata
def groups_that_may_match(md, column, minimum):
keep = []
for i in range(md.num_row_groups):
rg = md.row_group(i)
for j in range(rg.num_columns):
col = rg.column(j)
if col.path_in_schema != column:
continue
st = col.statistics
if st is None or not st.has_min_max or st.max >= minimum:
keep.append(i)
return keep
keep = groups_that_may_match(md, "id", 950_000)
print("row groups to read:", keep)
table = pf.read_row_groups(keep, columns=["id"])
print(table.num_rows)Only row group 9 survives, because every other group has a max below 950,000. The function keeps a group when statistics are missing. That is the safe default: a group with no statistics cannot be ruled out, so it must be read.
The table you read still contains all 100,000 rows of row group 9. Statistics work at group granularity, so the exact filter must still run on the rows that were read. The high-level call does both steps for you:
import pyarrow.parquet as pq
result = pq.read_table(
"events.parquet",
columns=["id"],
filters=[("id", ">=", 950_000)],
)
print(result.num_rows)This prints 50000. Compare it with the manual version: the manual version stopped at 100,000 rows, and the filtered call returns the 50,000 that satisfy the predicate.
Reading statistics critically
Statistics are hints written by the producer, so check these points before you rely on them.
- Missing statistics. A writer can turn them off. In PyArrow,
write_statistics=Falsedoes this. Some types or old files also lack them. Always testst is Noneandhas_min_max. - Null-only chunks. A chunk where every value is null has
has_min_maxequal toFalse. Readingst.minthere is not meaningful. - Unordered data. Statistics are exact for any order, but they only exclude groups when ranges are narrow. Unsorted or random data gives wide, overlapping ranges.
- Long strings and binary values. Some writers truncate min and max for long values. A truncated max is still a valid upper bound, but it may be looser than the real maximum.
- Floating point. NaN values complicate comparisons. Do not assume a clean range for float columns that contain NaN.
- Sizes are per chunk.
total_compressed_sizeincludes the dictionary page and data pages of that chunk only. Add across row groups to get the column's total.
Practical uses
- Check writer settings. Confirm that
num_row_groups, rows per group, andcompressionmatch what you configured. - Find the heavy columns. Sum
total_compressed_sizeper column across groups to see which column dominates file size. - Judge sort order. If
minandmaxof a column rise from one group to the next with no overlap, the file is sorted on it and filters on it will skip well. - Compare codecs. Rewrite a file with another codec and compare the sizes reported here, as you did in the compression chapter.
Exercise
You inspect a file with 20 row groups. For the column ts, the statistics of row group k show min and max ranges that all fall inside a single day, and the days increase with k. For the column user_id, every row group reports the same min and max. A query filters on ts for one day, and another filters on user_id = 42. Which query benefits from row group skipping based on min/max statistics, and why? What would you check first if the ts query still reads all 20 groups?
Show answer
The ts query benefits. Its row group ranges are narrow and do not overlap, so groups whose range excludes the target day can be skipped. The user_id ranges overlap fully, so min/max cannot exclude any group, and every group must be read. If the ts query still reads all 20 groups, first check the column's statistics: col.statistics may be None or has_min_max may be False (the writer may have disabled statistics). Then check that the reader pushed the filter down and that the filter's type matches the column type, for example a timestamp compared to a string.
Exercise
Write a short loop over pq.ParquetFile("events.parquet").metadata that prints the total compressed bytes per column summed across all row groups.
Show answer
Use a dictionary keyed by column name: totals = {} md = pq.ParquetFile("events.parquet").metadata for i in range(md.numrowgroups): rg = md.rowgroup(i) for j in range(rg.numcolumns): col = rg.column(j) totals[col.pathinschema] = totals.get(col.pathinschema, 0) + col.totalcompressedsize print(totals)