Parquet and Arrow
CSV stores a table row by row as text. That is easy for people but wasteful for machines: every read parses text again, guesses the types again, and has to scan every column even when you need two of them. Apache Parquet and Apache Arrow are the modern answer, and most large ML datasets (and the Hugging Face dataset hub) use them.
| Parquet | Arrow | |
|---|---|---|
| what | a file format on disk | an in-memory format |
| layout | columnar, compressed, with a schema | columnar, uncompressed, with a schema |
| used for | storing and sharing datasets | passing tables between libraries and processes without copying |
| in Python | pyarrow.parquet, pandas.read_parquet |
pyarrow.Table, pandas' Arrow-backed types |
The two work together: reading a Parquet file produces an Arrow table.
Columnar storage
A row-based file stores id, name, price for row 1, then for row 2, and so on. A columnar file stores all ids together, then all names, then all prices. Values of one column have the same type and are often similar, so they compress very well, and a query that needs only price can read just that column.
import pyarrow as pa
table = pa.table({
"id": pa.array([1, 2, 3], type=pa.int32()),
"city": pa.array(["Hanoi", "Hue", "Hanoi"]).dictionary_encode(),
"price": [9.5, 12.0, None],
"day": pa.array(["2026-05-01", "2026-05-02", "2026-05-02"]).cast(pa.date32()),
})
print(table.schema)
print()
print("rows:", table.num_rows, "| columns:", table.num_columns)
print("price column:", table.column("price").to_pylist(), "| nulls:", table.column("price").null_count)
print(table.to_pandas().dtypes.to_dict())id: int32
city: dictionary<values=string, indices=int32, ordered=0>
price: double
day: date32[day]
rows: 3 | columns: 4
price column: [9.5, 12.0, None] | nulls: 1
{'id': dtype('int32'), 'city': CategoricalDtype(categories=['Hanoi', 'Hue'], ordered=False, categories_dtype=object), 'price': dtype('float64'), 'day': dtype('O')}
The schema travels with the data: int32, a dictionary-encoded string column (each distinct city is stored once, rows hold small integer codes, like a pandas category), a nullable float and a real date type. Nothing has to be guessed when the table is read back. (pandas has no plain date type, so to_pandas turns the dates into Python date objects, dtype object; the Arrow table and a Parquet file keep date32.)
CSV vs Parquet on the same data
Let us store the same 20,000 sensor readings both ways, in memory:
import io
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
rng = np.random.default_rng(0)
n = 20_000
df = pd.DataFrame({
"sensor": pd.Categorical(rng.choice(["north", "south", "east", "west"], n)),
"time": pd.date_range("2026-01-01", periods=n, freq="min"),
"zip": pd.Series(rng.choice(["01067", "10115", "80331"], n), dtype="string"),
"temp_c": np.round(rng.normal(15, 5, n), 1),
"ok": rng.random(n) > 0.02,
})
csv_bytes = df.to_csv(index=False).encode()
pq_buf = io.BytesIO()
pq.write_table(pa.Table.from_pandas(df, preserve_index=False), pq_buf) # df.to_parquet(...) does the same
print(f"CSV: {len(csv_bytes) / 1024:7.0f} KiB")
print(f"Parquet: {len(pq_buf.getvalue()) / 1024:7.0f} KiB")
from_csv = pd.read_csv(io.BytesIO(csv_bytes))
from_pq = pq.read_table(io.BytesIO(pq_buf.getvalue())).to_pandas() # or pd.read_parquet(...)
print()
print(pd.DataFrame({"original": df.dtypes, "after CSV": from_csv.dtypes, "after Parquet": from_pq.dtypes}))
print()
print("zip after CSV:", from_csv["zip"].iloc[0], "| after Parquet:", from_pq["zip"].iloc[0])CSV: 808 KiB
Parquet: 211 KiB
original after CSV after Parquet
sensor category object category
time datetime64[ns] object datetime64[ns]
zip string[python] int64 string[python]
temp_c float64 float64 float64
ok bool bool bool
zip after CSV: 1067 | after Parquet: 01067
Parquet is about four times smaller (211 KiB against 808 KiB), and it brings back exactly the types that went in: the category, the timestamps, the zip codes as strings with their leading zeros. The CSV round trip lost all three; it would need the careful options from the CSV lesson every single time.
Reading only what you need
A Parquet file is split into row groups, and each row group stores, per column, statistics such as the minimum and maximum. A reader can skip columns it does not need (column projection) and skip row groups whose statistics rule them out (predicate pushdown):
import io
import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
rng = np.random.default_rng(1)
n = 10_000
table = pa.table({
"day": np.repeat(np.arange(1, 11), n // 10).astype("int32"),
"store": rng.integers(1, 51, n).astype("int32"),
"sales": np.round(rng.gamma(2.0, 30.0, n), 2),
"note": ["x" * 20] * n,
})
buf = io.BytesIO()
pq.write_table(table, buf, row_group_size=1_000)
data = buf.getvalue()
meta = pq.ParquetFile(io.BytesIO(data)).metadata
print("row groups:", meta.num_row_groups, "| rows:", meta.num_rows)
stats = meta.row_group(3).column(0).statistics
print("row group 3, column 'day': min", stats.min, "max", stats.max)
subset = pq.read_table(io.BytesIO(data), columns=["day", "sales"], filters=[("day", ">=", 9)])
print("read:", subset.num_rows, "rows x", subset.num_columns, "columns")
print("mean sales on days 9-10:", round(subset.column("sales").to_numpy().mean(), 2))row groups: 10 | rows: 10000
row group 3, column 'day': min 4 max 4
read: 2000 rows x 2 columns
mean sales on days 9-10: 59.86
The data was written sorted by day, so each row group covers a single day and the filter day >= 9 needs only the last two of the ten groups. On a dataset of hundreds of gigabytes, this is the difference between reading everything and reading a small slice. Sorting or partitioning data by the columns you filter on most (date, country) makes the skipping effective.
Partitioned datasets
Large Parquet datasets are usually a directory of files, partitioned by a column, with the value in the folder name (the "Hive" layout used by Spark, data lakes and DuckDB):
import os
import tempfile
import pyarrow as pa
import pyarrow.parquet as pq
import pyarrow.dataset as ds
table = pa.table({
"country": ["VN", "VN", "DE", "IN", "DE", "VN"],
"user": ["u1", "u2", "u3", "u4", "u5", "u6"],
"spent": [12.0, 30.5, 8.0, 15.0, 22.5, 9.0],
})
with tempfile.TemporaryDirectory() as root:
pq.write_to_dataset(table, root, partition_cols=["country"], basename_template="part-{i}.parquet")
for folder, _, files in sorted(os.walk(root)):
for f in sorted(files):
print(os.path.relpath(os.path.join(folder, f), root))
dataset = ds.dataset(root, format="parquet", partitioning="hive")
vn = dataset.to_table(filter=ds.field("country") == "VN")
print("VN users:", vn.column("user").to_pylist())country=DE/part-0.parquet
country=IN/part-0.parquet
country=VN/part-0.parquet
VN users: ['u1', 'u2', 'u6']
A query for Vietnam opens only the country=VN folder. The same layout works on object storage (S3, Google Cloud Storage), which the next lesson but one introduces.
When to use what
| Situation | Format |
|---|---|
| a small table people will open in a spreadsheet | CSV |
| nested records, API responses, logs | JSON / JSONL |
| analytics and ML training on tables of any real size | Parquet |
| passing a table between pandas, Polars, DuckDB, Spark in one process | Arrow |
Pitfalls
- Not human-readable. You need a tool to look inside; keep a small CSV sample or print the schema for people.
- Many tiny files (thousands of 10 KB files) are slow; aim for files of tens to hundreds of MB.
- Schema drift: files written at different times may have different types for the same column; check schemas before combining them.
- Updating rows: Parquet files are written once. Table formats on top of Parquet (Delta Lake, Apache Iceberg) add updates and versioning.
Practice
- Why does a columnar format compress a
countrycolumn with three distinct values so well?
Answer
All values of the column are stored together, and they repeat. Dictionary encoding stores the three strings once and each row as a tiny code; run-length encoding then compresses long runs of the same code to almost nothing.
- In the row-group example, how many row groups would
filters=[("day", "==", 5)]need to read?
Answer
One: row group 4 (counting from 0) holds all the rows of day 5, and the other nine have min/max statistics that exclude 5.
Test yourself
What is the main difference between Parquet and Arrow?
- Parquet is for images, Arrow for text
- Parquet is a compressed file format on disk, Arrow a columnar format in memory
- Arrow is row-based
- They are the same thing
Which information survives a Parquet round trip but not a plain CSV round trip?
- Column names
- Column types such as categories, timestamps and strings with leading zeros
- The number of rows
- Numeric values
What is predicate pushdown?
- Sorting the data before writing
- Skipping row groups whose min/max statistics show they cannot match a filter
- Compressing each column
- Converting Parquet to CSV
In a Hive-partitioned dataset, where is the value of the partition column stored?
- In every row of every file
- In the folder names, such as
country=VN/ - In a separate CSV
- Nowhere