Sub topic 11
Keeping categorical dtype when reading and writing files
This chapter assumes you can build categorical columns, read the .cat accessor, and use ordered categoricals. You also need to know how read_csv and to_csv work. The question here is what happens to a categorical column when it leaves memory and comes back. Some formats keep the dtype. Others silently turn it back into object, and sometimes into the wrong thing.
What a file format has to store
A categorical column has three parts: the category labels, the order of those labels, and an ordered flag. Each row also holds an integer code that points into the labels.
A file format keeps the dtype only if it can store all of that metadata. Plain text formats such as CSV cannot. They store one label per row and nothing else. Binary formats with a schema, such as Parquet, can record that a column is dictionary-encoded and so bring it back as categorical.
The table summarizes the common formats.
| Format | Keeps categorical dtype on round trip? | Notes |
|---|---|---|
| CSV | No | Rows are plain text labels. You must re-declare the dtype on read. |
| Parquet | Yes, with `pyarrow` | Categories are stored as a dictionary type. Category order may not be preserved exactly. |
| Feather | Yes, with `pyarrow` | Same dictionary mechanism as Parquet. |
| Pickle | Yes, exactly | Python-only. Do not load pickles from sources you do not trust. |
| HDF5 | Yes, with `format="table"` | Requires the PyTables package. |
| Stata | Yes, as value labels | Labels must be unique and fit Stata limits. |
CSV: the dtype is always lost
to_csv writes each category label as text. read_csv has no way to know the column was categorical, so it infers the usual dtypes.
import io
import pandas as pd
csv_text = """size,qty
small,1
large,2
medium,3
small,4
"""
df = pd.read_csv(io.StringIO(csv_text))
print(df.dtypes)size comes back as object. To get a categorical, pass dtype to read_csv, either for the whole file or per column.
import io
import pandas as pd
csv_text = """size,qty
small,1
large,2
medium,3
small,4
"""
df = pd.read_csv(io.StringIO(csv_text), dtype={"size": "category"})
print(df["size"].dtype)
print(df["size"].cat.categories)With dtype="category", pandas infers the categories from the data. They come out sorted, so here the order is large, medium, small. That is alphabetical order, which is wrong if your data has a logical order.
Reading directly into a categorical also saves memory. pandas builds the categories while parsing, so a large text column never exists as a full object column first. This helps most when the file is big and the column has few distinct values.
Declaring categories and order on read
Pass a CategoricalDtype instead of the string "category" when you know the valid categories. This fixes the category list, the order, and the ordered flag at read time.
import io
import pandas as pd
csv_text = """size,qty
small,1
large,2
medium,3
huge,4
small,5
"""
size_type = pd.CategoricalDtype(["small", "medium", "large"], ordered=True)
df = pd.read_csv(io.StringIO(csv_text), dtype={"size": size_type})
print(df["size"].dtype)
print(df["size"].tolist())
print(df["size"].isna().sum())The value huge is not in the declared categories, so it becomes a missing value (NaN) instead of raising an error. Check the number of missing values after the read, comparing it with a count taken before conversion if you can. A typo in the file is silently turned into missing data.
This silent conversion is also a validation tool. If you expect every row to be valid, a nonzero isna().sum() after reading tells you the file contained unexpected labels.
Numeric categories
With dtype="category", the categories are always read as strings, even when the column holds numbers. A column containing 1, 2, 3 gets the categories '1', '2', '3'.
If you pass a CategoricalDtype whose categories are all numbers, pandas converts the values to match.
import io
import pandas as pd
csv_text = """grade,name
1,a
3,b
2,c
1,d
"""
grade_type = pd.CategoricalDtype([1, 2, 3], ordered=True)
df = pd.read_csv(io.StringIO(csv_text), dtype={"grade": grade_type})
print(df["grade"].cat.categories)
print(df["grade"].max())The categories are integers here, so comparisons and max work on the logical order.
Converting after reading
You can also read normally and convert afterward with astype. This works, but it needs enough memory for the object column first, and the same dtype rules apply.
import io
import pandas as pd
csv_text = "size\nsmall\nlarge\n"
df = pd.read_csv(io.StringIO(csv_text))
df["size"] = df["size"].astype(pd.CategoricalDtype(["small", "large"], ordered=True))
print(df["size"].dtype)A reusable dictionary of dtypes keeps this consistent across files:
import pandas as pd
SCHEMA = {
"size": pd.CategoricalDtype(["small", "medium", "large"], ordered=True),
"region": pd.CategoricalDtype(["north", "south", "east", "west"]),
}
# df = pd.read_csv("orders.csv", dtype=SCHEMA)Passing the same SCHEMA for reading every file means all your DataFrames share identical categories. That makes later concatenation and merging safe, a point covered in the previous chapter on combining categoricals.
Parquet and Feather
Parquet and Feather are the usual choice when you want the dtype to survive. Both need the pyarrow package (fastparquet also handles Parquet). They store categoricals as dictionary-encoded columns and keep pandas metadata in the file.
import tempfile
from pathlib import Path
import pandas as pd
size_type = pd.CategoricalDtype(["small", "medium", "large"], ordered=True)
df = pd.DataFrame({
"size": pd.Series(["small", "large", "medium", "small"], dtype=size_type),
"qty": [1, 2, 3, 4],
})
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "orders.parquet"
df.to_parquet(path)
back = pd.read_parquet(path)
print(back["size"].dtype)
print(back["size"].cat.ordered)
print(list(back["size"].cat.categories))The column comes back as category. This also helps file size and read speed, since the file stores each distinct label once and the integer codes per row.
Do not assume everything is identical after the round trip. Parquet is a general format, and the category list and its order depend on how the dictionary is stored and read. In particular:
- Categories that appear in no row may be missing after reading.
- The category order may differ from the one you declared.
If the exact category list and order matter, restore them after reading:
import pandas as pd
size_type = pd.CategoricalDtype(["small", "medium", "large"], ordered=True)
# back = pd.read_parquet("orders.parquet")
# back["size"] = back["size"].astype(size_type)astype with a full CategoricalDtype reorders and re-labels the existing codes to match. Values not in the declared categories become missing, so this step also checks the data.
Feather works the same way with df.to_feather(path) and pd.read_feather(path). It is faster to read and write than Parquet but larger on disk, and it is mainly meant for short-term exchange between tools.
Pickle, HDF5, and Stata
Pickle stores the Python object itself, so the categories, order, and ordered flag all return unchanged. Use df.to_pickle(path) and pd.read_pickle(path). The cost is that pickle is tied to Python, can change between pandas versions, and can run arbitrary code when loaded. Only read pickles you created or fully trust.
HDF5 needs the PyTables package. Categorical columns are supported when you write with format="table":
import pandas as pd
df = pd.DataFrame({"size": pd.Series(["a", "b", "a"], dtype="category")})
# df.to_hdf("data.h5", key="orders", format="table")
# back = pd.read_hdf("data.h5", "orders")Stata files use a related idea called value labels. to_stata writes a categorical as integer codes plus labels. read_stata turns them back into categoricals by default (convert_categoricals=True). Stata limits what it accepts, so category labels must be unique strings of limited length. Check the pandas documentation for the current limits before relying on it.
Common problems
- Expecting CSV to remember the dtype. It never does. Always pass
dtypewhen reading, or convert right after. - Alphabetical categories from
dtype="category". The inferred categories are sorted, andorderedisFalse. UseCategoricalDtype([...], ordered=True)for logical order. - Silent
NaNvalues. Labels outside the declared categories are replaced by missing values. Count missing values after reading. - String categories for numeric data.
dtype="category"gives string categories. Declare numeric categories explicitly, or convert withpd.to_numericon the categories. - Assuming Parquet preserves unused categories and order. Re-apply your
CategoricalDtypeafter reading when these matter. - Trusting pickle from unknown sources. Loading a pickle can execute code.
Exercise
A CSV column level contains low, mid, high and one row with the typo hgih. You read it with dtype={"level": pd.CategoricalDtype(["low", "mid", "high"], ordered=True)}. What does the hgih row become, and how would you detect it?
Show answer
The hgih value is not in the declared categories, so it becomes missing (NaN) without an error. Detect it by checking df["level"].isna().sum() after reading, or by comparing against the count of missing values you expect (zero here).
Exercise
You save an ordered categorical column with to_parquet and read it back. Why should you still call astype with your original CategoricalDtype, and what does that call do?
Show answer
Parquet may not preserve unused categories or the exact category order. Calling astype(original_dtype) restores the full category list, the order, and the ordered flag. It also turns any value outside the categories into a missing value, which acts as a check on the data.