Sub topic 2
Creating categorical columns
This chapter assumes you can build pandas Series and DataFrames, know dtypes such as int64 and object, and have used groupby and value_counts. It covers the ways to create a categorical column and what happens to values that don't fit the categories.
Four ways to get a categorical
A categorical column stores a fixed list of categories plus an integer code per row. You can create one at four points in your workflow.
Converting with astype
astype("category") is the most common route. pandas finds the unique values, sorts them, and uses them as the categories.
import pandas as pd
df = pd.DataFrame({"size": ["small", "large", "medium", "small", "large"]})
df["size"] = df["size"].astype("category")
print(df["size"].dtype)
print(list(df["size"].cat.categories))The output is category, then ['large', 'medium', 'small']. The categories come out in alphabetical order, not in the logical order of small, medium, large. A later chapter covers ordering. For now, remember that inferred categories are always sorted.
Declaring the dtype up front
You can pass dtype="category" when you build a Series. You can also pass it per column when reading a file. The reader never creates a full object column first.
import io
import pandas as pd
s = pd.Series(["red", "green", "red"], dtype="category")
csv = io.StringIO("color,count\nred,3\ngreen,5\nred,2\n")
df = pd.read_csv(csv, dtype={"color": "category"})
print(s.dtype)
print(df.dtypes)Fixing the categories with CategoricalDtype
pd.CategoricalDtype lets you state the categories yourself. This matters when the data might not contain every valid value, or when several datasets must share the same categories.
import pandas as pd
level = pd.CategoricalDtype(["low", "mid", "high"])
s = pd.Series(["low", "high", "low"], dtype=level)
print(list(s.cat.categories))
print(s.value_counts())The categories are ['low', 'mid', 'high'], in the order you gave. Even though "mid" never occurs in the data, it stays a category and appears in value_counts() with a count of 0.
Building with pd.Categorical
pd.Categorical creates the underlying array directly. Wrap it in a Series or assign it to a column.
import pandas as pd
cat = pd.Categorical(["x", "y", "x"], categories=["x", "y", "z"])
s = pd.Series(cat)
print(s.dtype)
print(s.cat.codes.tolist())The codes are [0, 1, 0]. Each code is the position of the value in the categories list.
Values outside the categories become NaN
When you supply categories, any value not on the list is replaced by NaN. pandas does not raise an error.
import pandas as pd
allowed = pd.CategoricalDtype(["low", "high"])
s = pd.Series(["low", "mid", "high"], dtype=allowed)
print(s.isna().tolist())The output is [False, True, False]. The value "mid" was silently lost.
Choosing a method
| Situation | Method |
|---|---|
| Convert a column you already have | `astype("category")` |
| Let the categories be inferred | `dtype="category"` |
| Large file, avoid building `object` columns | `read_csv(dtype=...)` |
| Known valid values, shared across datasets | `pd.CategoricalDtype([...])` |
| Need codes and categories explicitly | `pd.Categorical(values, categories=...)` |
Common errors
- Expecting inferred categories to follow logical order. They are sorted alphabetically or numerically.
- Converting a column with mostly unique values, such as IDs. You get no memory saving, and the category list becomes as large as the data.
- Creating separate dtypes from
astype("category")in two DataFrames and then combining them. Each gets its own inferred categories, which causes trouble later. Create oneCategoricalDtypeand reuse it.
Exercise
You run pd.Series(["a", "b", "c"], dtype=pd.CategoricalDtype(["a", "b"])). What is the third element, and why does pandas not raise an error?
Show answer
The third element is NaN. The value "c" is not in the declared categories, and pandas represents any value outside the categories as a missing value instead of raising an error. Check isna().sum() after conversion to catch this.