Sub topic 10
How Parquet keeps dtypes and what it cannot store
This chapter assumes you can write a DataFrame with to_parquet and have pyarrow installed (pip install pyarrow). It also assumes you know the pandas dtypes int64, float64, string, category, and datetime64. Here you will learn why a Parquet round trip returns the same dtypes that CSV loses, and which data Parquet refuses to store.
Where the dtypes are stored
A CSV file holds only text. Whoever reads it must guess whether 2026-01-05 is a string or a date. A Parquet file stores a schema next to the data. The schema names each column and gives its physical type, such as 64-bit integer, double, boolean, string, or timestamp.
The pyarrow engine adds one more layer. It writes a small JSON entry named pandas into the file's metadata. This entry records what Arrow types alone cannot express: the index layout, nullable extension dtypes, and the original column names. read_parquet uses the schema and this metadata to rebuild the DataFrame.
A round trip that keeps its dtypes
The next script builds a DataFrame with nullable integers, nullable strings, an ordered categorical, a nullable boolean, and a timezone-aware datetime. It writes the frame to Parquet and reads it back.
import pandas as pd
df = pd.DataFrame({
"order_id": pd.array([1, 2, None], dtype="Int64"),
"customer": pd.array(["Ana", "Ben", None], dtype="string"),
"tier": pd.Categorical(
["gold", "basic", "gold"], categories=["basic", "gold"], ordered=True
),
"paid": pd.array([True, False, None], dtype="boolean"),
"ordered_at": pd.to_datetime(
["2026-01-05", "2026-01-06", "2026-01-07"]
).tz_localize("Europe/Berlin"),
})
df.to_parquet("typed.parquet", engine="pyarrow", index=False)
back = pd.read_parquet("typed.parquet")
print(df.dtypes.equals(back.dtypes))
print(back.dtypes)The first print shows True. The second shows Int64, string, category, boolean, and datetime64[ns, Europe/Berlin]. Exact output can vary slightly with your pandas version. For example, pandas 3 changes the default string dtype.
Now write the same frame to CSV and read it back:
df.to_csv("typed.csv", index=False)
csv_back = pd.read_csv("typed.csv")
print(csv_back.dtypes)Here order_id becomes float64, because the missing value forces floats. customer, tier, paid, and ordered_at all become object. The ordered categories and the timezone are gone. You would have to repair each column with dtype= and parse_dates=, and the timezone could not be restored this way at all.
What is preserved
The table compares the two formats for common dtypes.
| Dtype | After a CSV round trip | After a Parquet round trip (pyarrow) |
|---|---|---|
| `int64`, `float64`, `bool` | Usually kept, unless missing values force a change | Kept |
| `Int64`, `boolean` (nullable) | Becomes `float64` or `object` | Kept |
| `string` | Becomes `object` | Kept |
| `category` (with order) | Becomes `object` | Kept, including categories and order |
| `datetime64[ns]` | `object` unless `parse_dates` is used | Kept |
| Timezone-aware datetime | `object`, offset text only | Kept, with the zone name |
| Missing values | Empty text or `na_rep` marker | Stored as null |
Missing values deserve a note. Parquet marks them as nulls in every column type, not with a sentinel text. A float64 column with NaN comes back as float64 with NaN. An Int64 column with <NA> comes back as Int64 with <NA>. A plain int64 column cannot hold a missing value in the first place, so no dtype change happens on disk.
How the index is handled
The index argument of to_parquet defaults to None, which behaves differently from index=True:
- A default
RangeIndexis stored only as metadata (start, stop, step), not as a column. - Any other index, such as a string index or a
MultiIndex, is written as one or more extra columns and restored as the index on read. index=Truewrites the index as a column even when it is aRangeIndex.index=Falsedrops the index entirely, andread_parquetreturns a freshRangeIndex.
indexed = df.set_index("customer")
indexed.to_parquet("indexed.parquet") # index stored as a column
print(pd.read_parquet("indexed.parquet").index.name)This prints customer. Two cautions follow from this behavior:
- Check the index before you compare a restored frame with the original. A frame whose index was dropped can look equal in its columns and still differ in its index.
- A named non-default index can surprise readers who open the file with another tool, because they will see an extra column.
What Parquet cannot store
Parquet is strict about types. Many failures come from pandas object columns, which can hold anything and so have no single Parquet type.
Mixed types in one column
A column that mixes numbers and strings has no single type. The pyarrow engine raises an error during conversion instead of guessing:
import pandas as pd
import pyarrow as pa
messy = pd.DataFrame({"value": [1, "two", 3.5]})
try:
messy.to_parquet("messy.parquet", engine="pyarrow")
except (pa.ArrowInvalid, pa.ArrowTypeError) as exc:
print("Cannot write:", type(exc).__name__)The fix is to decide on one type before writing. Use astype("string") if the column is really text, or pd.to_numeric(..., errors="coerce") if it should be numeric. Do not use astype(str) blindly. It turns missing values into the text "nan" or "None".
Arbitrary Python objects
Parquet has no type for custom classes, sets, Decimal mixed with floats, or functions. Convert them to a supported type first, for example a string with str, or a JSON string with json.dumps when you need to keep structure.
Lists and dictionaries are a special case. The pyarrow engine can store them as nested list and struct types if every row has the same shape. They come back as NumPy arrays and dictionaries, so a list column does not round trip as a list. The fastparquet engine has weaker support for nested data. For portable files, flatten nested values into columns or JSON text.
Column names
Column names must be strings. A frame with integer column names raises ValueError: parquet must have string column names. Duplicate column names are also rejected. Rename them first:
numbered = pd.DataFrame([[1, 2], [3, 4]])
numbered.columns = numbered.columns.astype(str)
numbered.to_parquet("numbered.parquet")The columns come back named "0" and "1" as strings, not integers. Convert them yourself after reading if you need integers.
Data that changes in transit
Some conversions succeed but alter your data:
- Index levels are written as columns, so a column whose name collides with an index level name can cause trouble.
- Timestamps outside the range a file format supports can be rejected or truncated. Check the
coerce_timestampsandallow_truncated_timestampsarguments ofpyarrowif you work with very old or distant dates. - Different engines write nullable dtypes differently. A file written with
pyarrowand read withfastparquetmay not give the same dtypes.
Choosing the dtype backend on read
read_parquet accepts dtype_backend (pandas 2.0 and later). It controls which dtypes the result uses when the file has no pandas metadata, or when you want a different representation:
numpy_nullable = pd.read_parquet("typed.parquet", dtype_backend="numpy_nullable")
arrow_backed = pd.read_parquet("typed.parquet", dtype_backend="pyarrow")
print(arrow_backed.dtypes)With dtype_backend="pyarrow", columns are held as Arrow arrays, with dtypes like int64[pyarrow] and string[pyarrow]. This can save memory for string-heavy data. Some pandas operations still run faster on NumPy-backed columns, so measure before you switch.
Selecting columns to save work
Parquet is column-oriented, so reading a subset is cheap. The columns argument reads only what you name:
subset = pd.read_parquet("typed.parquet", columns=["order_id", "paid"])
print(subset.dtypes)Dtypes of the chosen columns are unchanged. This is one reason Parquet beats CSV for wide tables: CSV must parse every line in full even when you want two columns.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `ArrowInvalid` or `ArrowTypeError` on write | Mixed types in an `object` column | Cast the column to one type |
| `ValueError: parquet must have string column names` | Integer or other non-string column labels | `df.columns = df.columns.astype(str)` |
| `ImportError` mentioning `pyarrow` or `fastparquet` | No Parquet engine installed | `pip install pyarrow` |
| Restored frame has an unexpected `RangeIndex` | Written with `index=False` | Write with `index=True`, or reset the index into a column first |
| Dtypes differ between tools | Other tools ignore pandas metadata | Test the file in the tool that will read it |
Exercises
Exercise
A DataFrame has a column score that contains the values 10, "n/a", and 7.5. to_parquet with the pyarrow engine raises an error. Give two reasons the write fails and one way to fix it.
Show answer
The column has dtype object with integers, a string, and a float, so it has no single Parquet type, and pyarrow does not guess a type that fits every value. Fix it before writing: convert to numbers with df["score"] = pd.to_numeric(df["score"], errors="coerce"), which turns "n/a" into NaN, or convert the whole column to text with df["score"].astype("string").
Exercise
You write a frame with an Int64 column, a category column, and a timezone-aware datetime column to CSV and to Parquet. After reading each file back with default arguments, which dtypes does each file return?
Show answer
The CSV file returns float64 (if there are missing values) or int64 for the integer column, object for the category column, and object for the datetime column with the timezone only as text. The Parquet file, written and read with pyarrow, returns Int64, category (with its categories and order), and datetime64[ns, <zone>].
Exercise
A frame has a default RangeIndex. You call df.to_parquet("a.parquet") and then df.to_parquet("b.parquet", index=True). How do the files differ?
Show answer
In a.parquet the RangeIndex is saved only as metadata (start, stop, step), so the file has no index column. In b.parquet the index is written as an extra column named __index_level_0__, and other tools see it as data. Both files restore the same index when read with pandas.