In pandas, why does assigning 'Delighted' into an ordered satisfaction-scale categorical column raise TypeError, and how do you add the new answer properly?
answer
- a closed set of allowed values
- set the categories first
- the .cat accessor's add method
- where an appended category ranks
basics
~10 sA pandas categorical accepts only values already in its categories, so setting 'Delighted' raises TypeError. Add it first with s.cat.add_categories(['Delighted']), which appends it as the highest level, or use set_categories to place it elsewhere.
solid answer
~40 sA categorical's categories are a closed list, so `__setitem__`, `loc` and `fillna` only accept values already in it or a missing value; anything else raises `TypeError: Cannot setitem on a Categorical with a new category (Delighted), set the categories first`. The fix is to change the dtype before the data: `s = s.cat.add_categories(['Delighted'])` appends it, which in an ordered scale makes it the highest level, then the assignment works. To put it in a specific position I use `s.cat.set_categories([...full list...], ordered=True)`, remembering that `set_categories` silently turns any value missing from the new list into NaN. In pandas 3.0, casting raw text with `astype(scale)` still turns unknown answers into NaN but now emits a `Pandas4Warning` saying it will raise in a future version.
code
python · 16 linesimport pandas as pd
scale = pd.CategoricalDtype(
["Very unsatisfied", "Unsatisfied", "Neutral", "Satisfied", "Very satisfied"],
ordered=True,
)
answers = pd.Series(["Satisfied", "Neutral", "Very satisfied"], dtype=scale)
try:
answers[0] = "Delighted"
except TypeError as err:
print(err)
answers = answers.cat.add_categories(["Delighted"])
answers[0] = "Delighted"
print(answers.cat.categories[-1], answers.max())go deeper
Recall that a categorical only accepts values already in its categories, and that add_categories must come before the assignment.
Explain the .cat methods: add appends, reorder keeps the same set, set_categories replaces the list and silently turns missing values into NaN.
Know the pandas 3.0 deprecation of out-of-list values on cast, why imported modules hide its warning, and validate answers against the scale before casting.
Decide who owns each scale's category list, so adding a level is a reviewed change rather than a side effect of whichever pipeline meets it first.
## Categories are a closed set A pandas **categorical** stores a list of allowed values, the **categories**, and an integer **code** per row pointing into that list. A row can only hold one of those categories or a missing value (code `-1`). Because the codes can only point at existing entries, pandas refuses to store anything else. That is why every way of writing a value into an existing categorical checks membership first: - `s[0] = 'Delighted'` and `df.loc[mask, 'answer'] = 'Delighted'`; - `s.fillna('No answer')`, which writes the fill value into the missing rows. Both raise `TypeError: Cannot setitem on a Categorical with a new category (Delighted), set the categories first`. Assigning another categorical whose categories differ is refused too, with `TypeError: Cannot set a Categorical with another, without identical categories`. Setting a missing value is always allowed. ## Changing the categories with the `.cat` accessor The fix is always to change the dtype first, then the data. The `.cat` accessor returns a new Series for each change: | Method | What it does | Where it bites | |---|---|---| | `add_categories(['Delighted'])` | appends new categories at the end | raises `ValueError` if a value is already a category | | `set_categories([...], ordered=...)` | replaces the whole list in one step | values missing from the new list silently become NaN | | `rename_categories({...})` | relabels categories, rows follow | positions do not move, so order is unchanged | | `reorder_categories([...])` | same set, new order | raises `ValueError` if the set differs | | `remove_categories([...])` | drops categories | rows holding them become NaN | | `remove_unused_categories()` | drops categories with no rows | none; often run after filtering | For an **ordered** scale, position is meaning. `add_categories` appends, so 'Delighted' lands after 'Very satisfied' and becomes the maximum. If it belongs between two existing levels, rebuild the list: ```python scale = scale_series.cat.set_categories( ["Very unsatisfied", "Unsatisfied", "Neutral", "Satisfied", "Delighted", "Very satisfied"], ordered=True, ) ``` Check the counts before and after: `set_categories` does no spelling checks, so a typo in the new list turns every row with that answer into NaN without a warning. ## Values outside the categories when casting Assignment raises, but **construction and casting** behave differently. When raw text is cast with an explicit dtype, ```python answers.astype(pd.CategoricalDtype(levels, ordered=True)) ``` any answer that is not in `levels` becomes NaN. In pandas 2.x this happened silently. In **pandas 3.0** it still produces NaN but emits a `Pandas4Warning`: "Constructing a Categorical with a dtype and values containing non-null entries not in that dtype's categories is deprecated and will raise in a future version." Two practical consequences: 1. `Pandas4Warning` is a subclass of `DeprecationWarning`, and Python's default warning filters show those only for code running in `__main__`. A cast inside an imported pipeline module therefore stays silent unless warnings are enabled, for example in the test suite. 2. Code that relied on the cast to drop junk answers will break when the deprecation is enforced, so map unknown answers explicitly before casting, for example with `where(s.isin(levels))`. ## A safe sequence for a survey scale 1. Define the scale once as a `CategoricalDtype(levels, ordered=True)`. 2. Before casting, list the answers that are not in `levels` (`~s.isin(levels)`), and decide for each: fix the spelling, map it to an existing level, or add a level. 3. To add a level, update the shared `levels` list in its correct position and recast; for a one-off column, `add_categories` followed by `reorder_categories` works. 4. After any category change, compare `s.isna().sum()` before and after to catch values that turned into NaN. ## Why pandas is strict here The strictness protects the meaning of the codes. If assignment could quietly append a category, an ordered scale would gain a new maximum by accident, and a column that was cast with a shared dtype would no longer match it, so comparisons against other columns of that scale would start raising. Making the category change explicit keeps every frame that shares the dtype in agreement about what each code means and where it ranks.
- Why does fillna('No answer') on a categorical column raise the same TypeError?`fillna` writes the fill value into the missing rows, which is a set-item operation on the categorical. 'No answer' is not a category, so it is refused like any other assignment. Add it first with `s.cat.add_categories(['No answer'])`, or fill with an existing category.
- What is the difference between rename_categories and set_categories with rename=True?`rename_categories` relabels each category and needs either a mapping or a list of the same length, raising `ValueError` on a length mismatch or duplicates. `set_categories(new, rename=True)` also relabels by position but accepts a list of a different length: extra entries become unused categories, and if the list is shorter the rows coded beyond it become NaN.
A categorical column is like a printed survey form with fixed tick boxes: nobody can tick a box that is not printed. To accept a new answer you reprint the form with the extra box first, and a box added at the end of the scale reads as the top answer.
- Assigning a new value to a categorical adds it as a category automatically
- add_categories inserts a new level in alphabetical position within the order
- set_categories raises an error when existing values are missing from the new list
- In pandas 3.0 astype with a CategoricalDtype already raises on unknown values
- The fix for the TypeError is to cast the column back to str permanently
pandas 2.x silently turned values outside a CategoricalDtype's categories into NaN on construction or astype; pandas 3.0 still does so but deprecates it with a Pandas4Warning.