Sub topic 1
Why categorical data exists
Prerequisites
This chapter assumes you can write basic Python and create and index pandas Series and DataFrames. You should know the common dtypes such as int64 and object, and have used groupby and value_counts. Later chapters cover the details of creating and managing categoricals. This one explains why the dtype exists and when it helps.
The problem with repeated strings
Many real columns hold a small set of values repeated many times. Examples are country, status, product size, and survey answers. By default pandas stores text in an object column. Each row holds a reference to a separate Python string, so a million rows of "small", "medium" and "large" carry a million string references.
This causes three costs:
- Memory grows with the number of rows, not with the number of distinct values.
- Comparisons and grouping work on strings, which is slower than working on integers.
- Nothing tells pandas or the reader that the column only allows a fixed set of values, or that the values have an order.
The working model
A categorical column splits the data into two parts:
- Categories: the sorted list of distinct values, stored once.
- Codes: one small integer per row, pointing to a position in the categories.
The next diagram shows how a column of sizes maps to codes.
The categories are sorted alphabetically by default, so "large" gets code 0. Row values are rebuilt by looking up each code in the categories. The code below shows this on a small column.
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]The dtype is category. The categories are large, medium and small. The codes match the diagram.
What you gain
Memory
Codes use a small integer type, and each distinct string is stored once. With few distinct values and many rows, the saving is large. You can measure it with memory_usage(deep=True), which counts the memory of the Python string objects as well as the column itself.
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))
print(s_cat.memory_usage(deep=True))The exact numbers depend on your pandas version and platform. The categorical result is far smaller, because it holds 300,000 one-byte codes plus three strings.
Speed
Operations such as groupby, value_counts and equality tests can work on the integer codes instead of comparing strings. The benefit grows with the number of rows and shrinks as the number of distinct values approaches the number of rows.
Meaning
A categorical records that the column has a fixed set of allowed values. You can also mark the categories as ordered, so small < medium < large holds and sorting follows that order instead of alphabetical order. Later chapters cover ordering in detail.
When it does not help
Categoricals are not always better. Avoid them when:
- Most values are unique, such as IDs, free text, or timestamps. The categories list then becomes as large as the data, and you save nothing.
- The column is small. The saving is too little to matter.
- You will do heavy arithmetic or string operations on the values. Those work on the categories first, so they can add overhead or need extra care.
A rough test is to compare s.nunique() with len(s). If the distinct count is a small fraction of the row count, a categorical is a good candidate.
Summary of the idea
A categorical trades a flat list of strings for a lookup table plus integer codes. You get lower memory, faster grouping, and a way to express a fixed or ordered set of values. The next chapter shows the ways to create categorical columns.
Exercise
A DataFrame has 2 million rows. Column A has 5 distinct values. Column B holds a unique order ID per row. Which column should you convert to a categorical, and why?
Show answer
Convert column A. It has few distinct values repeated many times, so the categories list is tiny and the integer codes save memory and speed up grouping. Column B has as many distinct values as rows, so the categories list would be as large as the data and nothing would be saved.
Exercise
In the example with sizes small, large, medium, small, large, why does "small" get code 2?
Show answer
pandas sorts the distinct values alphabetically to build the categories: large, medium, small. A code is the position in that list, and "small" is at position 2.