Sub topic 9
Saving a DataFrame to Parquet
This chapter assumes you can build and inspect a DataFrame, run Python scripts or notebooks, install packages with pip, and recognize column dtypes such as int, float, string, and datetime. You should also have seen to_csv in the earlier chapters. Here you write your first Parquet file, learn what the main arguments do, and read the file back selectively.
What Parquet is and why it behaves differently from CSV
Parquet is a binary, columnar file format. "Binary" means you cannot open it in a text editor and read it. "Columnar" means the values of each column are stored together instead of row by row. Each file also carries a schema, which records every column's name and type.
Three consequences matter for everyday work:
- Types travel with the data. An integer column comes back as integers and a datetime column comes back as datetimes. You do not pass
parse_datesordtypewhen reading. - Files are usually much smaller than the same data in CSV, because similar values sit together and compress well.
- You can read only the columns you need, and often only the row groups you need, without parsing the whole file.
The cost is that people cannot inspect the file with basic tools. Spreadsheet users cannot open it directly either. Choose Parquet when the next reader is code (another pandas script, Spark, DuckDB, a data warehouse), not a person.
Install a Parquet engine
pandas does not write Parquet itself. It hands the work to an engine, which is a separate library. Two are supported:
pyarrowis the usual choice. It is actively maintained and supports the widest range of types and options.fastparquetis a lighter alternative.
Install one of them:
pip install pyarrowIf neither is installed, to_parquet raises an ImportError that tells you to install one.
Write your first file
The following script builds a small DataFrame with text, missing values, floats, and dates, then saves it:
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 3],
"customer": ["Ana", "Ben", None],
"amount": [19.99, 5.5, None],
"ordered_at": pd.to_datetime(["2026-01-05", "2026-01-06", "2026-01-07"]),
})
df.to_parquet("orders.parquet", index=False)
back = pd.read_parquet("orders.parquet")
print(back.dtypes)The printed dtypes show order_id as an integer, amount as a float, and ordered_at as a datetime64 type. The missing value in customer is still missing. None of this needed extra arguments, which is the main practical difference from the CSV round trip.
Two behaviors are worth knowing now:
to_parquetsilently overwrites an existing file at the same path. It never appends to a single file.- The file extension has no effect on the format. Use
.parquetanyway, because other tools rely on the convention.
How the engine is chosen
With the default engine="auto", pandas tries pyarrow first and falls back to fastparquet. If you want the same behavior on every machine, name the engine explicitly.
df.to_parquet("orders.parquet", engine="pyarrow", index=False)Pinning the engine matters because the two libraries differ in edge cases, such as which types they can store. A file written by one engine can usually be read by the other, but pinning removes one source of surprise in a team or a deployment.
The signature in practice
The arguments you will use most are these:
| Argument | Default | What it does |
|---|---|---|
| `path` | required | File path, URL such as `s3://...`, file-like object, or `None` to return bytes |
| `engine` | `"auto"` | `"pyarrow"`, `"fastparquet"`, or automatic choice |
| `compression` | `"snappy"` | Codec used inside the file. The compression chapter covers the options |
| `index` | `None` | Whether to write the index. See the next section |
| `partition_cols` | `None` | Columns used to split the output into a directory of files. Covered later |
| `storage_options` | `None` | Extra settings for remote storage such as credentials |
Any other keyword arguments are passed through to the engine.
Control what happens to the index
The index is the most common source of confusion with Parquet. The index argument has three modes:
index=None(the default). A plainRangeIndex(0, 1, 2, ...) is stored as lightweight metadata, not as a column. Any other index is written as a real column.index=True. The index is always written as a column.index=False. The index is dropped.
With the default, the index is restored when you read the file, so a round trip keeps a meaningful index:
by_id = df.set_index("order_id")
by_id.to_parquet("orders_by_id.parquet")
restored = pd.read_parquet("orders_by_id.parquet")
print(restored.index.name) # order_idThe index is written as a column, and pandas records in the file's metadata that this column is the index. read_parquet uses that metadata to rebuild it.
An unnamed non-range index shows up in other tools as a column called __index_level_0__. This happens, for example, after you filter rows with df[df["amount"] > 5], because the remaining labels (0, 1) no longer form a clean range in every case. If another system will read the file, this stray column surprises people.
A good habit is to decide deliberately. Use index=False when the index is just row numbers. Call reset_index() first when the index holds real data you want as a normal, named column. Use the default only when pandas is the sole consumer and you want the index back.
Read back only what you need
Because Parquet is columnar, read_parquet can skip columns without reading them:
slim = pd.read_parquet("orders.parquet", columns=["order_id", "amount"])
print(slim)With the pyarrow engine you can also push row filters into the read. Filters are a list of (column, operator, value) tuples, and all tuples in the list must hold at the same time:
big = pd.read_parquet(
"orders.parquet",
engine="pyarrow",
filters=[("amount", ">", 10)],
)
print(big)Only the order with an amount above 10 is returned. Rows with a missing amount do not match the comparison, so they are excluded. Filters work best on files that are sorted or partitioned by the filtered column, because the engine can then skip whole blocks of data. On an unsorted file they still give the right answer but save less work.
Write to memory or to remote storage
Passing path=None returns the file as bytes, which is handy for uploading through an API:
payload = df.to_parquet(index=False)
print(type(payload), len(payload) > 0)You can also write to a file-like object, which is useful in tests:
import io
buffer = io.BytesIO()
df.to_parquet(buffer, index=False)
buffer.seek(0)
print(pd.read_parquet(buffer).shape)For cloud paths such as s3://bucket/orders.parquet, pandas delegates to the fsspec family of libraries. You need the matching package installed, for example s3fs for S3. Credentials go in storage_options, or come from the environment as usual for that provider.
Common errors and fixes
Most failures come from the data, not from the call itself. These are the ones you will meet first:
| Symptom | Cause | Fix |
|---|---|---|
| `ImportError` mentioning `pyarrow` or `fastparquet` | No engine installed | `pip install pyarrow` |
| `ValueError: parquet must have string column names` | Column labels are integers or tuples | `df.columns = df.columns.astype(str)` |
| `ArrowTypeError` or `ArrowInvalid` on a text-looking column | An `object` column mixes types, such as strings and numbers | Convert it first, for example `df["code"] = df["code"].astype("string")` |
| Index comes back as an extra column in another tool | Non-range index written by default | Use `index=False`, or `reset_index()` and name the column |
| Old data appears in the output | The file was overwritten by a previous run, or you read a stale path | Write to a new path or confirm the path before reading |
The mixed-type case deserves a closer look, because it is the one that surprises people who come from CSV. CSV stores everything as text, so a column holding 1, "x", and 2.5 is fine. Parquet requires one type per column, so pandas must be able to map the whole column to a single type. Clean such columns before writing. Decide whether the column is text or numeric, and convert it with astype or pd.to_numeric.
The next chapter looks at exactly which dtypes Parquet preserves and which ones it cannot store, so only the basic idea is needed here.
Practical checklist
Before you save a result to Parquet:
- Install an engine and, for reproducibility, name it with
engine="pyarrow". - Make column names strings.
- Ensure each column holds one kind of value.
- Choose the index mode on purpose.
- Read the file back and compare it with the original. A later chapter shows how.
Exercise
You run df.query("amount > 5").to_parquet("big.parquet") on a DataFrame with the default RangeIndex, using the default index argument. A colleague opens the file in a non-pandas tool and finds an unexpected column named __index_level_0__. Why did it appear, and what are two ways to prevent it?
Show answer
Filtering removes rows, so the remaining labels are no longer a clean 0, 1, 2, ... RangeIndex. With index=None, pandas stores only a plain RangeIndex as metadata and writes any other index as a real column. The unnamed index is therefore written as __index_level_0__. To prevent it, pass index=False when the index is only row numbers, or call reset_index(drop=True) before writing. If the old labels hold real data, call reset_index() and rename the new column to something meaningful instead.
Exercise
Write df to orders.parquet, then read back only the customer and amount columns, keeping only rows where amount is greater than 10. Which engine must you use for the row filter, and what happens to rows with a missing amount?
Show answer
Use df.to_parquet("orders.parquet", engine="pyarrow", index=False), then pd.read_parquet("orders.parquet", engine="pyarrow", columns=["customer", "amount"], filters=[("amount", ">", 10)]). The filter argument as shown here is used with the pyarrow engine. Rows whose amount is missing do not satisfy the comparison, so they are not returned.