Sub topic 3
Saving a DataFrame to Parquet
Assume you know basic Python, pandas DataFrames, and common dtypes such as integers, strings, floats, and datetimes. Parquet is a binary, column-oriented file format. It is usually a better choice than CSV for analytical data because it stores column types and often produces smaller files.
Saving a DataFrame to Parquet
Use to_parquet to write a DataFrame. The pyarrow or fastparquet package is required.
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 3],
"amount": [19.99, 5.50, 12.00],
"ordered_at": pd.to_datetime(["2026-01-05", "2026-01-06", "2026-01-07"]),
})
df.to_parquet("orders.parquet", engine="pyarrow", index=False)The index=False argument prevents the pandas index from becoming an extra column.
Dtypes and storage limits
Parquet records schema information, so integers, floats, strings, booleans, and datetimes usually survive a round trip without extra parsing arguments. A CSV reader instead sees text and must infer or convert types.
Parquet is not a general-purpose Python object store. Arbitrary objects, functions, open files, and mixed object columns cannot reliably be stored. Convert such values to supported types first.
Compression and partitioned datasets
Compression reduces storage and I/O, with a CPU cost. Common choices include snappy for speed and zstd for stronger compression. A partitioned dataset stores separate directories for selected column values.
sales.to_parquet(
"sales_parquet",
engine="pyarrow",
compression="zstd",
partition_cols=["country"],
)For example, pandas can create directories such as country=DE and country=FR. Partitioning helps readers skip unrelated data.
Writing large results in chunks
A single DataFrame may use too much memory. For large CSV input, process chunks and write each result incrementally. Parquet datasets are commonly built from batches with a compatible Arrow writer rather than appended with repeated to_parquet calls.
for i, chunk in enumerate(pd.read_csv("input.csv", chunksize=100_000)):
result = transform(chunk)
result.to_csv(
"output.csv",
mode="w" if i == 0 else "a",
header=(i == 0),
index=False,
)Verify the written file
Read the file back and compare it with the original.
restored = pd.read_parquet("orders.parquet")
pd.testing.assert_frame_equal(df, restored)Exercise
Why might you choose Parquet instead of CSV for a DataFrame containing datetimes?
Show answer
Parquet stores schema and datetime information, so the values can usually be restored without manually parsing the column.