Sub topic 11
Keeping categorical dtype when reading and writing files
This chapter assumes you can create categoricals with astype("category") and CategoricalDtype, and that you know the .cat accessor. It covers what happens to a categorical column when it is saved to a file and loaded again.
Why dtype gets lost
A categorical is a pandas concept. Plain text formats such as CSV have no place to record "this column has categories, in this order". When you write a categorical column to CSV, each row becomes its text label. When you read the file back, pandas sees strings and gives you object. The category order, the ordered flag, and any unused categories are gone.
Binary formats can store more. Parquet and Feather keep dictionary-encoded columns, and pickle stores the whole pandas object.
Reading CSV with a categorical dtype
Pass dtype to read_csv. With the string "category", pandas infers the categories from the file and sorts them. With a CategoricalDtype, you choose the categories and their order.
import io
import pandas as pd
csv_text = "size,qty\nsmall,3\nlarge,5\nmedium,2\nsmall,1\n"
inferred = pd.read_csv(io.StringIO(csv_text), dtype={"size": "category"})
print(list(inferred["size"].cat.categories)) # ['large', 'medium', 'small']
size_type = pd.CategoricalDtype(["small", "medium", "large"], ordered=True)
df = pd.read_csv(io.StringIO(csv_text), dtype={"size": size_type})
print(list(df["size"].cat.categories)) # ['small', 'medium', 'large']
print(df["size"].max()) # largeThe inferred categories are alphabetical, which is rarely the logical order. Use an explicit dtype whenever order matters.
Round trip through CSV
Writing and re-reading shows the loss directly:
import io
import pandas as pd
size_type = pd.CategoricalDtype(["small", "medium", "large"], ordered=True)
df = pd.DataFrame({"size": pd.Series(["small", "large"], dtype=size_type)})
buffer = io.StringIO()
df.to_csv(buffer, index=False)
buffer.seek(0)
plain = pd.read_csv(buffer)
print(plain["size"].dtype) # object (or str in newer pandas)
buffer.seek(0)
restored = pd.read_csv(buffer, dtype={"size": size_type})
print(restored["size"].dtype == size_type) # TrueThe fix is to keep the dtype definition in your code and pass it on every read. Defining the CategoricalDtype objects once, in a shared module, keeps writers and readers consistent.
Parquet and Feather
Parquet and Feather store a categorical as a dictionary of values plus integer codes, which mirrors how pandas holds it in memory. This needs the pyarrow package.
import pandas as pd
size_type = pd.CategoricalDtype(["small", "medium", "large"], ordered=True)
df = pd.DataFrame({"size": pd.Series(["small", "large", "small"], dtype=size_type)})
df.to_parquet("sizes.parquet")
back = pd.read_parquet("sizes.parquet")
print(back["size"].dtype) # category
print(list(back["size"].cat.categories)) # ['small', 'medium', 'large']
print(back["size"].cat.ordered) # Trueto_feather and read_feather behave the same way. Both formats also store the file more compactly than CSV and load faster, so they suit intermediate results in a pipeline.
Choosing a format
| Format | Keeps categorical dtype | Keeps order and `ordered` | Notes |
|---|---|---|---|
| CSV | No | No | Pass `dtype` on every read |
| Parquet | Yes | Yes | Needs `pyarrow`, good for sharing |
| Feather | Yes | Yes | Fast, best for temporary files |
| Pickle | Yes | Yes | Python only, do not load untrusted files |
Exercise
You save a DataFrame with an ordered categorical column "grade" to CSV, then read it back with pd.read_csv(path, dtype={"grade": "category"}). Comparisons like df["grade"] >= "B" now raise an error. Why, and how do you fix it?
Show answer
CSV does not store the ordered flag or category order. Passing "category" infers unordered categories in alphabetical order, so order comparisons are not allowed. Define pd.CategoricalDtype([...], ordered=True) with the logical order and pass it as the dtype, or save to Parquet or Feather so the dtype is stored in the file.