Sub topic 2
Creating categorical columns
This chapter covers the ways to build a categorical column in pandas and the choices you make when you do. It assumes you can create Series and DataFrames, know dtypes such as int64 and object, and have used groupby and value_counts. The next chapter looks at what pandas stores inside the column after you create it.
The four entry points
A categorical column holds a fixed list of categories plus one integer code per row. You can create one in four main ways:
- Convert an existing column with
astype("category"). - Declare the dtype when you build a Series or DataFrame, or when you read a file.
- Build a
pd.Categoricalobject directly, then wrap it in a Series. - Produce one from numbers with
pd.cutorpd.qcut, which are covered in a later chapter.
The first three differ in one thing: who decides the categories. With plain "category", pandas infers them from the data. With CategoricalDtype or pd.Categorical(..., categories=...), you decide.
| Method | Categories come from | Ordered by default |
|---|---|---|
| `astype("category")` | Sorted unique values in the data | No |
| `dtype="category"` in a constructor | Sorted unique values in the data | No |
| `pd.CategoricalDtype([...])` | The list you pass | No (`ordered=True` to change) |
| `pd.Categorical(values, categories=[...])` | The list you pass, or inferred if omitted | No |
| `pd.Categorical.from_codes(codes, categories)` | The list you pass | No |
Converting with astype
The simplest route converts a column you already have.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Oslo", "Cairo", "Lima"],
"temp": [3, 19, 1, 28, 21],
})
df["city"] = df["city"].astype("category")
print(df.dtypes)
print(list(df["city"].cat.categories)) # ['Cairo', 'Lima', 'Oslo']
print(df["city"].cat.codes.tolist()) # [2, 1, 2, 0, 1]Three things happen here:
- pandas finds the unique values and sorts them. Those become the categories.
- The sort is alphabetical for strings and numeric for numbers. It is not the order in which the values first appear.
- Each row now stores the position of its value in that list, so
"Oslo"is stored as2.
The result is unordered. Comparing df["city"] < "Lima" raises a TypeError, which is intended, because cities have no natural order.
Converting several columns at once is easiest with a dictionary passed to astype.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Oslo"],
"country": ["NO", "PE", "NO"],
"temp": [3, 19, 1],
})
df = df.astype({"city": "category", "country": "category"})
print(df.dtypes)Naming the columns keeps the conversion explicit, so you never convert an identifier column by accident.
Declaring the dtype up front
If you already know a column should be categorical, say so when you create the data. This skips the intermediate object column.
import pandas as pd
s = pd.Series(["b", "a", "b", "c"], dtype="category")
df = pd.DataFrame(
{"color": ["red", "blue", "red"], "n": [1, 2, 3]},
dtype=None,
).astype({"color": "category"})
print(s.cat.categories.tolist()) # ['a', 'b', 'c']
print(df["color"].dtype) # categoryThe dtype= argument of the DataFrame constructor applies to every column, so for mixed frames, convert per column with astype as shown. The Series constructor has only one column to worry about, so dtype="category" works directly.
Controlling categories with CategoricalDtype
Inference has a weakness. If a rare value is missing from this month's data, it is missing from the categories too, and two files with different values end up with different dtypes. pd.CategoricalDtype fixes the category list in advance.
import pandas as pd
size_type = pd.CategoricalDtype(["small", "medium", "large"])
s = pd.Series(["small", "large", "medium", "small"], dtype=size_type)
print(s.cat.categories.tolist()) # ['small', 'medium', 'large']
print(s.cat.codes.tolist()) # [0, 2, 1, 0]
print(s.dtype == size_type) # TrueThe categories stay in the order you wrote them, not alphabetical order. The code for "large" is 2 because it is third in your list.
You can reuse one dtype object across many columns and many files. Two categorical dtypes compare equal when they have the same categories and the same ordered flag. Later chapters rely on this when combining data.
Values outside the categories become missing
import pandas as pd
size_type = pd.CategoricalDtype(["small", "medium", "large"])
s = pd.Series(["small", "large", "huge", "medium"], dtype=size_type)
print(s.tolist()) # ['small', 'large', nan, 'medium']
print(s.isna().sum()) # 1A quick guard is to check the data against the dtype before converting:
import pandas as pd
size_type = pd.CategoricalDtype(["small", "medium", "large"])
raw = pd.Series(["small", "large", "huge", "medium"])
unknown = set(raw.dropna()) - set(size_type.categories)
if unknown:
print("Not in categories:", sorted(unknown)) # Not in categories: ['huge']Rules for the category list
The list you give must follow three rules:
- Categories must be unique. Duplicates raise a
ValueError. - Categories cannot contain
NaNorNone. Missing values are never categories. They are stored as code-1. - Categories can be any hashable type, and numeric categories keep their numeric type.
Numbers deserve a warning. pd.Series([1, 2, 1, 3]).astype("category") gives categories 1, 2, 3, but the column no longer supports arithmetic. Adding 1 to it raises a TypeError. If the numbers are quantities rather than labels, leave them as numbers.
Building a pd.Categorical directly
pd.Categorical is the array object that sits inside a categorical Series. You can build it yourself and pass it to a Series or assign it to a column.
import pandas as pd
c = pd.Categorical(
["b", "a", "b"],
categories=["a", "b", "c"],
ordered=True,
)
s = pd.Series(c, name="grade")
print(c.codes.tolist()) # [1, 0, 1]
print(s.cat.ordered) # True
print(s.cat.categories.tolist()) # ['a', 'b', 'c']Note that "c" is a category even though no row uses it. Unused categories are legal and sometimes wanted, for example to keep a report showing every grade including empty ones. The groupby chapter returns to this.
The constructor accepts categories=, ordered=, or a dtype= argument. Pass either dtype or the other two, not both.
Building from integer codes
If your data already holds integer codes, as in a database export with a lookup table, from_codes avoids a round trip through strings.
import pandas as pd
c = pd.Categorical.from_codes(
[0, 2, 1, 0, -1],
categories=["low", "mid", "high"],
)
print(list(c)) # ['low', 'high', 'mid', 'low', nan]Each code must be -1 (missing) or a valid position in categories. A code of 3 here would raise a ValueError.
Reading files straight into categoricals
read_csv accepts a dtype per column, so large text columns never exist as object in memory.
import io
import pandas as pd
csv = io.StringIO("name,grade\nAnn,B\nBob,A\nCy,B\nDee,C\n")
grade_type = pd.CategoricalDtype(["A", "B", "C", "D"], ordered=True)
df = pd.read_csv(csv, dtype={"grade": grade_type})
print(df["grade"].dtype) # category
print(df["grade"].cat.categories.tolist()) # ['A', 'B', 'C', 'D']
print(df["grade"].max()) # CHere category "D" appears in the dtype but not in the file, and it is kept. This is the main reason to pass a CategoricalDtype instead of the string "category". A later chapter covers saving and loading categoricals in more detail.
Deciding which columns to convert
Not every text column benefits. Conversion pays off when a column has few distinct values compared with its length. An identifier column where nearly every value is unique gains nothing and costs extra, because pandas stores both the categories and the codes.
A helper that converts only low-cardinality text columns:
import pandas as pd
def to_category(df: pd.DataFrame, max_ratio: float = 0.5) -> pd.DataFrame:
out = df.copy()
for col in out.columns:
if pd.api.types.is_string_dtype(out[col]):
ratio = out[col].nunique() / len(out)
if ratio <= max_ratio:
out[col] = out[col].astype("category")
return out
df = pd.DataFrame({
"user_id": ["u1", "u2", "u3", "u4", "u5", "u6"],
"plan": ["free", "pro", "free", "free", "pro", "free"],
})
print(to_category(df).dtypes) # user_id stays text, plan becomes categoryThe 0.5 threshold is a starting point, not a rule. Measure memory on your own data before settling on one. That is the subject of the chapter after next.
Common errors when creating categoricals
- Unexpected
NaNafter conversion. The value was not in the declared categories. Check spelling, case, and stray spaces withstr.strip()before converting. ValueError: Categorical categories must be unique. The list has duplicates. Uselist(dict.fromkeys(items))to remove them while keeping order.ValueError: Categorical categories cannot be null. RemoveNaNandNonefrom the list.- Different dtypes across files. Each file inferred its own categories. Define one
CategoricalDtypeand reuse it. - A
TypeErroron comparison. The categorical is unordered. Create it withordered=Trueif the order is real. - Numbers that stop working. A numeric column converted to categorical no longer supports arithmetic. Convert back with
astypeto a numeric dtype, or never convert it.
Exercise
You run pd.Series(["S", "M", "XL", "M"], dtype=pd.CategoricalDtype(["S", "M", "L"])). What does the Series contain, and what are its codes?
Show answer
The values are ['S', 'M', NaN, 'M'], because "XL" is not in the categories and is silently replaced by missing. The codes are [0, 1, -1, 1], since -1 marks the missing value.
Exercise
A CSV has a status column with the values open, closed, and pending, but this month's file contains only open and closed. How do you load it so the column always has all three categories, in the order open, pending, closed?
Show answer
Define status_type = pd.CategoricalDtype(["open", "pending", "closed"]) and call pd.read_csv(path, dtype={"status": status_type}). The categories come from the dtype, not from the data, so pending is kept even when no row uses it.