As the lead of a team whose pandas pipelines carry many low-cardinality text columns, would you make converting them to category at load time a standard, and what does that rule cost?
answer
- codes plus one copy of each label
- only for low cardinality
- new labels raise TypeError
- concat with other categories falls back
- observed=True hides empty groups
basics
~20 sNot as a blanket rule. Category saves memory and speeds grouping on low-cardinality columns, but new labels raise on assignment, concat and merge with different categories fall back to str, and 3.0's observed=True drops empty groups. I would allow it for listed columns with fixed category sets.
solid answer
~50 sA categorical stores one integer code per row plus each distinct label once, so a column like store region or size can shrink sharply and group faster. The costs come from the fixed category set. Assigning a label that is not a category raises `TypeError`. `pd.concat` of two monthly files whose categories differ gives a `str` column in 3.0 (`object` in 2.x), so the type erodes at the first append unless `union_categoricals` or a shared `CategoricalDtype` is used, and merges on keys with different categories lose it too. Since 3.0, `groupby` defaults to `observed=True`, so unused categories vanish from reports unless `observed=False` is passed. CSV round trips drop the dtype; Parquet keeps it. My rule: category only for named columns, each with one shared `CategoricalDtype` defined in the loader, plus dtype assertions at pipeline boundaries.
code
python · 18 linesimport io
import pandas as pd
from pandas.api.types import union_categoricals
jan = pd.read_csv(io.StringIO("store,size\nS1,M\nS2,L\n"), dtype={"size": "category"})
feb = pd.read_csv(io.StringIO("store,size\nS1,XL\nS3,M\n"), dtype={"size": "category"})
both = pd.concat([jan, feb], ignore_index=True)
print(both["size"].dtype)
sizes = union_categoricals([jan["size"], feb["size"]])
print(sizes.dtype, list(sizes.categories))
try:
jan.loc[0, "size"] = "XS"
except TypeError as err:
print("TypeError:", err)go deeper
Know that category stores codes plus distinct labels and that it suits columns with few distinct values.
Explain why assigning a new label raises, and how read_csv's dtype argument and CategoricalDtype declare categories up front.
Diagnose dtype erosion through concat and merge, and the 3.0 observed default dropping empty groups.
Set a scoped standard: an allowlist of columns, shared dtype definitions, explicit observed where reports need it, measurement before adoption and dtype assertions at boundaries.
## What the standard would buy A `category` column keeps an array of small integer codes and a separate list of the distinct labels. For a column with a handful of values repeated across millions of rows, such as a region, a size or a status, that is far smaller than storing every string, and grouping on it works with the codes. Reading it in that form is one argument: `read_csv(..., dtype={'size': 'category'})`. The argument for a team standard is that memory and grouping speed improve everywhere without each author remembering to convert. ## What it costs | Situation | What happens with category | Why it matters | |---|---|---| | High-cardinality column, such as an ID | codes **plus** every label: larger, not smaller | a blanket rule makes some columns worse | | Assigning a label that is not a category | `TypeError`: cannot setitem with a new category | fixes and backfills fail until categories are added | | `pd.concat` of two files whose categories differ | the column becomes `str` in 3.0, `object` in 2.x | the dtype erodes silently on the first append | | `merge` on keys with different categories | the key column comes back as `str` | downstream code that expects category breaks | | `groupby` on a category column in 3.0 | `observed=True` by default: unused categories are dropped | a report loses its zero rows | | Writing to CSV and reading back | the dtype is gone | every consumer must re-declare it | | Writing to Parquet and reading back | the category dtype is kept | the safe hand-off format | The grouping change is the one most teams meet during the 3.0 upgrade: pandas 2.1 deprecated the old `observed=False` default and 3.0 changed it to `True`. A report that relied on empty categories to show "XL: 0 sales" quietly stops showing that row. ## The rule I would set 1. **An allowlist, not a blanket conversion.** The loader converts only named columns whose set of values is small and known: sizes, regions, status codes. Free text and identifiers stay as `str`. 2. **One `CategoricalDtype` per column, defined once.** The loader declares `pd.CategoricalDtype([...], ordered=...)` for each listed column and every reader uses it. Two monthly files then share the same categories, so `concat` keeps the dtype, and ordered columns such as sizes compare correctly. 3. **Combine with `union_categoricals` when categories really differ**, rather than letting `concat` fall back. 4. **Say which groupings must show empty categories.** Reports that list every size or region pass `observed=False` explicitly; everything else accepts the 3.0 default. 5. **Assert dtypes at boundaries.** A test on key outputs checks that the listed columns are still categorical, so an erosion through `concat` or `merge` fails CI instead of surfacing as a memory spike. 6. **Hand data between jobs in Parquet**, where the dtype survives, not CSV. ## Where the rule lives A rule that lives only in a style guide is forgotten by the second new hire. The dtype definitions belong in the shared loading module, next to the readers that use them, so a column joins the allowlist in one place and every job picks it up. Review then has one question to ask of a new pipeline: does it read through the loader? Ad hoc `astype('category')` calls further down a pipeline are the exception that needs a reason, because each one creates a category set nobody else shares, and the next `concat` or `merge` with another job's output undoes it. ## How I would decide Measure first. `df.memory_usage(deep=True)` before and after conversion on a real day's data shows which columns are worth it, and a timing of the main grouped aggregations shows whether grouping speed matters for this pipeline at all. If neither memory nor grouping is a bottleneck, the operational costs above can outweigh the gain, and plain `str` columns are the simpler standard. ## What a strong answer sounds like It names the benefit and the conditions for it, lists the ways the dtype breaks or erodes, including the 3.0 `observed` change, and ends with a scoped rule: an allowlist, shared dtype definitions, explicit `observed` where reports need it, and dtype checks that keep the rule true over time.
- How do you stop concat from turning the monthly size columns back into text?Give every file the same categories: define one `CategoricalDtype` with the full label list in the loader and read each file with it, so `concat` sees identical dtypes and keeps `category`. When the sets really differ, combine the columns with `union_categoricals`, or convert both to a shared dtype with `astype` before concatenating.
- Why define the CategoricalDtype once in the loader instead of calling astype('category') in each job?Each `astype('category')` call infers its categories from the data it happens to see, so two jobs give the same column two different category sets. The first `concat` or `merge` between their outputs then falls back to text, and the memory saving disappears without an error. One declared dtype gives every job the same categories, and the same order for an ordered column.
- Converting every object or str column to category to save memory
- Expecting concat to keep category when the files' categories differ
- Assuming a CSV round trip preserves the category dtype
- Calling astype('category') separately in every job instead of sharing one dtype
- Fixing a new label by assigning it directly into the categorical column
Assumes pandas 3.0, where groupby defaults to observed=True and concatenating categoricals with different categories falls back to the str dtype; in 2.x observed defaulted to False and the fallback was object.