In pandas, why does df[df['satisfaction'] >= 'Satisfied'] filter one survey file correctly but raise TypeError on another file with the same column?
answer
- how each file built the column
- ordered versus unordered
- the scalar must be a category
- one shared CategoricalDtype
basics
~20 sAn inequality on a pandas categorical needs ordered=True and a scalar that is one of its categories. One file's column was cast with the ordered scale; the other was left unordered by astype('category'), or the label is misspelled, so pandas raises TypeError.
solid answer
~40 sComparing a categorical with `<`, `<=`, `>` or `>=` compares **positions in the categories list**, so pandas allows it only when the categorical is ordered. The working file was cast with the shared `CategoricalDtype(levels, ordered=True)`; the failing one was probably built with `astype('category')`, which is unordered, giving `TypeError: Unordered Categoricals can only compare equality or not`. The same filter also raises when 'Satisfied' is not a category, for example a casing difference, with `Invalid comparison between dtype=category and str`, and when two categorical columns with different categories are compared. If the column had stayed `str`, it would not raise at all but compare text, so 'Unsatisfied' would pass the filter. I fix it by casting every source with one shared dtype.
code
python · 17 linesimport pandas as pd
levels = ["Very unsatisfied", "Unsatisfied", "Neutral", "Satisfied", "Very satisfied"]
raw = pd.Series(["Satisfied", "Unsatisfied", "Very satisfied", "Neutral"])
scaled = raw.astype(pd.CategoricalDtype(levels, ordered=True))
print((scaled >= "Satisfied").tolist())
unordered = raw.astype("category")
for label, s, rhs in [("unordered", unordered, "Satisfied"),
("typo", scaled, "satisfied")]:
try:
s >= rhs
except TypeError as err:
print(label, "->", err)
print((raw >= "Satisfied").tolist())go deeper
Recall that only an ordered categorical supports <, >, <= and >=, and that the label you compare against must be one of its categories.
Explain that comparisons use positions in the categories list, list the TypeError messages and their causes, and why equality behaves differently.
Diagnose from the dtypes of both files, spot the silent text comparison on an uncast str column, and fix it with one shared dtype at load time.
Make ordered scales part of the data contract, so every loader applies the same dtype and a filter cannot change meaning with the file it reads.
## What an inequality means on a categorical A pandas **categorical** stores a **categories** list and an integer **code** per row. When the categorical is **ordered**, the list is a ranking: `['Very unsatisfied', 'Unsatisfied', 'Neutral', 'Satisfied', 'Very satisfied']` means each value outranks the ones before it. An inequality such as `s >= 'Satisfied'` is answered by comparing codes against the position of 'Satisfied', never by comparing the text. The pandas user guide lists exactly three comparisons that work: 1. `==` and `!=` against a list-like of the same length; 2. all six comparison operators against another categorical, when it is ordered and the categories are the same; 3. all comparisons against a scalar. Everything else, especially an inequality between two categoricals with different categories or between a categorical and a plain list or array, raises `TypeError`. The scalar case has its own conditions, covered next. ## The four ways the same filter fails | Situation | What happens | |---|---| | Column is unordered (built with `astype('category')`) | `TypeError: Unordered Categoricals can only compare equality or not` | | Scalar is not a category (typo, casing, trailing space) | `TypeError: Invalid comparison between dtype=category and str` | | Other side is a categorical with different categories | `TypeError: Categoricals can only be compared if 'categories' are the same.` | | Other side is a list or non-categorical array | `TypeError: Cannot compare a Categorical for op __ge__ with type ...` | Rows two to four assume an ordered column; on an unordered one the first message fires before any of them. Equality is more forgiving: `s == 'satisfied'` against a scalar that is not a category returns all `False` rather than raising, which can hide the same typo in an equality filter. ## The silent failure is worse If one file's column never became categorical, it stays a pandas 3.0 `str` column, and `>=` compares **text**. No error is raised, but the meaning is wrong: - 'Unsatisfied' >= 'Satisfied' is `True`, because 'U' sorts after 'S'; - 'Neutral' >= 'Satisfied' is `False`, which happens to look right; - 'Very unsatisfied' >= 'Satisfied' is `True`. So the file that "works" may be the broken one. Check the dtype (`df['satisfaction'].dtype`) on both files before trusting either result. ## Diagnosing the failing file 1. Print `df['satisfaction'].dtype`. A `CategoricalDtype(..., ordered=False)` or a `str` dtype tells you the column was not built with the scale. 2. Print `df['satisfaction'].cat.categories.tolist()` and compare it with the expected list: a different order, extra spellings or a missing level each change the comparison. 3. Check the scalar: `'Satisfied' in df['satisfaction'].cat.categories`. 4. If two columns are compared with each other, compare their dtypes; `CategoricalDtype` instances are equal only when both the categories and the ordered flag match (order of categories is ignored only for unordered ones). ## The fix that lasts Define the scale once and use it everywhere the column enters the program: ```python SATISFACTION = pd.CategoricalDtype(levels, ordered=True) df["satisfaction"] = df["satisfaction"].astype(SATISFACTION) ``` - Pass the same dtype to the reader's `dtype=` argument or cast right after loading; a CSV file stores only the text, so the order never survives a round trip on its own. - If you must compare against values that are not in the scale, convert explicitly, for example with `np.asarray(cat)`, and accept that the comparison is then textual. - An existing column with the right categories but `ordered=False` can be fixed with `s.cat.as_ordered()`; one with the right set in the wrong order with `s.cat.reorder_categories(levels, ordered=True)`. ## What else the ordered scale gives you Once the column carries the ordered dtype, the rest of pandas reads the same ranking from it: - `sort_values` lists answers from 'Very unsatisfied' to 'Very satisfied'; - `min()` and `max()` return the lowest and highest answer given; - a groupby on the column lists groups in scale order rather than alphabetically; - the same filter means the same thing on every file, because each one reads the same categories. That consistency is the real argument for casting at load time: one dtype decision fixes sorting, reductions, grouping and filtering together. ## Why pandas refuses rather than guessing An unordered categorical has a categories list, but that order is an accident of inference, usually alphabetical. Letting `>=` use it would quietly reproduce the text-comparison bug. Raising forces the author to state the order, which is the whole point of an ordered categorical: the ranking lives in the dtype, not in the spelling of the labels.
- Two ordered categorical columns, before and after, are compared with after > before and raise TypeError. What do you check?Their categories. Comparing two categoricals needs both ordered and the same categories; one column likely gained or lost a level, or was cast with a different list. Print both `cat.categories`, then cast both with one shared `CategoricalDtype` so the codes mean the same thing on each side.
- Why does s == 'satisfied' not raise when s >= 'satisfied' does?For a scalar outside the categories, pandas follows Python's convention for mismatched comparisons: equality returns all `False`, inequality (`!=`) all `True`, and ordering comparisons raise `TypeError`. So an equality filter with a misspelled label silently selects nothing, which is worth guarding with an explicit membership check.
- Any categorical column supports >= against a label in it
- Comparisons on an ordered categorical sort the labels alphabetically
- A label outside the categories simply compares as False for >=
- A plain str column with >= ranks survey answers by meaning
- Two ordered categoricals compare fine as long as both are ordered