Sub topic 1
Why categorical data exists
Many real columns hold a small set of labels that repeat across thousands or millions of rows. Examples are country, order status, T-shirt size, or survey answer. pandas stores text like this as the object dtype by default, and object knows nothing about the repetition. This chapter explains what goes wrong with object columns and what the categorical dtype changes. Later chapters cover the mechanics in detail.
Prerequisites
This chapter assumes you can do the following:
- Read and write basic Python, including list literals and
print. - Create a pandas
SeriesorDataFrameand select a column. - Recognize common dtypes such as
int64andobject. - Use
value_countsand a simplegroupby.
You do not need to know anything about categoricals yet.
The problem with object columns
When pandas reads a column of strings, it usually gives it the object dtype. Each cell is a pointer to a separate Python string. This design is flexible, because an object column can hold anything. But the flexibility costs you in four ways.
Repeated values are stored repeatedly
If a column of 1,000,000 rows contains only the values "red", "green", and "blue", an object column still keeps a reference per row. The set of distinct values is never recorded anywhere. Every operation that needs it, such as groupby or unique, has to rediscover it by hashing and comparing strings.
The column has no notion of allowed values
Nothing stops a typo from entering the data. The next example shows how an object column treats three spellings of the same size.
import pandas as pd
s = pd.Series(["small", "Small", "smal", "small"])
print(s.value_counts())pandas counts "small", "Small", and "smal" as three separate groups. Any report built on this column is quietly wrong, and no error tells you so.
Text order is not logical order
Sorting strings sorts them alphabetically. For sizes, that gives the wrong answer.
import pandas as pd
df = pd.DataFrame({"size": ["small", "large", "medium", "small", "large"]})
print(df["size"].dtype) # object
print(df["size"].sort_values().tolist()) # ['large', 'large', 'medium', 'small', 'small']The logical order is small, medium, large. Alphabetical order puts large first and small last. A comparison like df["size"] >= "medium" would also use string comparison, which is meaningless here.
Missing categories disappear
Suppose a survey allows the answers low, mid, and high, but nobody answered mid this week. A groupby or value_counts on an object column simply omits mid. The column cannot report a group it has never seen, so a downstream table or chart may silently lose a row.
What a categorical dtype changes
A categorical column splits the data into two parts:
- Categories are the distinct allowed values, stored once.
- Codes are small integers, one per row. Each code is a position in the categories list.
The column's dtype also carries the categories. The dtype therefore describes the set of allowed values, not only the storage type.
Here is the same column converted:
import pandas as pd
df = pd.DataFrame({"size": ["small", "large", "medium", "small", "large"]})
df["size"] = df["size"].astype("category")
print(df["size"].dtype)
print(df["size"].cat.categories)
print(df["size"].cat.codes.tolist()) # [2, 0, 1, 2, 0]By default, pandas sorts the unique values to build the categories: large, medium, small. The code 2 means "the third category", which is small. The next chapters cover creation and the .cat accessor in detail. Here, notice only that each distinct string is stored once and every row holds a small integer.
The benefits
Each benefit follows from the two-part structure.
Lower memory use
Integer codes are much smaller than per-row string references. The saving is largest when a few distinct values repeat many times. You can verify this on your own data:
import pandas as pd
n = 300_000
s_obj = pd.Series(["red", "green", "blue"] * (n // 3))
s_cat = s_obj.astype("category")
print(s_obj.memory_usage(deep=True) > s_cat.memory_usage(deep=True)) # TrueUse deep=True so that pandas counts the string contents and not only the pointers. A later chapter measures the gain properly.
Faster operations
Many operations can work on the integer codes and touch the strings only at the end. Grouping, counting, and equality tests on integers are cheaper than on strings. The speed-up depends on the operation and the data, so measure before relying on it.
Validation of allowed values
When you give a categorical dtype an explicit list of categories, values outside that list cannot be stored. They become missing values instead.
import pandas as pd
allowed = pd.CategoricalDtype(["small", "medium", "large"])
s = pd.Series(["small", "Small", "large"], dtype=allowed)
print(s.isna().tolist()) # [False, True, False]"Small" with a capital S is not in the list, so it becomes NaN. This is a feature when you want bad values to surface. It is a trap if you did not expect the conversion to drop data, so always check isna().sum() after converting with an explicit dtype.
Meaningful order
A categorical can be marked as ordered. Comparisons, min, max, and sorting then follow the order you defined, not the alphabet.
import pandas as pd
size_type = pd.CategoricalDtype(["small", "medium", "large"], ordered=True)
s = pd.Series(["small", "large", "medium", "small"], dtype=size_type)
print((s >= "medium").tolist()) # [False, True, True, False]
print(s.max()) # large
print(s.sort_values().tolist()) # ['small', 'small', 'medium', 'large']Known groups, including empty ones
Because the dtype remembers all categories, some operations can report categories that have zero rows. This keeps tables and charts complete. It can also surprise you, and the chapter on groupby covers it.
import pandas as pd
level = pd.CategoricalDtype(["low", "mid", "high"])
s = pd.Series(["low", "low", "high"], dtype=level)
print(s.value_counts())The output includes mid with a count of 0.
When a categorical is a good fit
Use these checks before converting a column.
| Check | Good sign | Bad sign |
|---|---|---|
| Number of distinct values | Small compared with the number of rows | Close to one distinct value per row |
| Value set | Fixed or slowly changing | Open-ended, such as free text or IDs |
| Meaning | Labels, groups, or ranked levels | Values you add, subtract, or do arithmetic on |
| Workload | Repeated grouping, sorting, or filtering | Written once and rarely used |
A column of unique customer IDs is a poor candidate. Each value is distinct, so the categories list is as long as the column, and the codes only add overhead. A column of country names across a million orders is a strong candidate.
Common errors at this stage
These mistakes appear often when people first meet categoricals.
- Converting everything. Applying
astype("category")to every string column can make memory use worse for high-cardinality columns. Cardinality means the number of distinct values. - Assuming categories are ordered. A plain categorical sorts by its category list, which defaults to alphabetical. It does not support meaningful
<or>comparisons until you setordered=True. - Forgetting that unknown values become missing. An explicit dtype silently turns values outside the list into
NaN. - Treating codes as data. The integer codes are an internal index into the categories. Their numbers change if the categories change, so do not store them as a stable identifier.
- Doing arithmetic. A categorical of numbers such as
[1, 2, 3]is still a set of labels. You cannot sum it directly.
How the rest of the tutorial builds on this
The remaining chapters take each idea above in turn. You will create categoricals, work with categories and codes through the .cat accessor, measure memory and speed, and use ordered categoricals. You will also manage categories safely, handle missing values, bin numbers with cut and qcut, and choose the right observed setting in groupby. The last chapters cover combining categoricals, file formats, encoding for models, and a checklist of pitfalls.
Exercise
A table has 2,000,000 rows. The column country has 40 distinct values. The column order_id has 2,000,000 distinct values. Which column is a better candidate for the categorical dtype, and why? Name one further benefit besides memory that you get if you also give country an explicit list of allowed values.
Show answer
country is the better candidate. It has few distinct values that repeat many times, so storing each name once and using small integer codes saves memory and speeds up grouping. order_id has one distinct value per row, so a categorical would not save memory. It would only add a categories list as long as the column. With an explicit list of allowed values for country, misspelled or unexpected values become missing values instead of silently forming new groups. Another valid answer is that empty categories can still appear in value_counts results.
Exercise
You run pd.Series(["low", "high", "mid"]).sort_values() and get ['high', 'low', 'mid']. What two steps would make pandas return ['low', 'mid', 'high']?
Show answer
Create a CategoricalDtype with the categories listed in the logical order and ordered=True, for example pd.CategoricalDtype(["low", "mid", "high"], ordered=True). Then build or convert the Series with that dtype, as in pd.Series([...], dtype=that_dtype), and call sort_values(). Sorting then follows the category order, not the alphabet.