pandas-dev/pandas · error · TypeError
'values' is not ordered, please explicitly specify the categ
Error message
'values' is not ordered, please explicitly specify the categories order by passing in a categories argument.
What it means
Raised when `ordered=True` is requested but the values cannot be sorted (factorize with sort=True raises TypeError), so pandas cannot infer a deterministic category order. The fix is to supply the categories explicitly so their order defines the ranking rather than relying on sortability of the raw values.
Source
Thrown at pandas/core/arrays/categorical.py:485
categories = arr.dictionary.to_pandas(types_mapper=ArrowDtype)
codes = arr.indices.to_numpy()
dtype = CategoricalDtype(categories, values.dtype.pyarrow_dtype.ordered)
else:
preserve_object = False
if isinstance(values, (ABCIndex, ABCSeries)) and values.dtype == object:
# GH#61778
preserve_object = True
if not isinstance(values, ABCIndex):
# in particular RangeIndex xref test_index_equal_range_categories
values = sanitize_array(values, None)
try:
codes, categories = factorize(values, sort=True)
except TypeError as err:
codes, categories = factorize(values, sort=False)
if dtype.ordered:
# raise, as we don't have a sortable data structure and so
# the user should give us one by specifying categories
raise TypeError(
"'values' is not ordered, please "
"explicitly specify the categories order "
"by passing in a categories argument."
) from err
if preserve_object:
# GH#61778 wrap categories in an Index to prevent dtype
# inference in the CategoricalDtype constructor
from pandas import Index
categories = Index(categories, dtype=object, copy=False)
# if not preserve_object, we're inferring from values
dtype = CategoricalDtype(categories, dtype.ordered)
elif isinstance(values.dtype, CategoricalDtype):
old_codes = extract_array(values)._codes
codes = recode_for_categories(View on GitHub (pinned to 71959b8cb9)
Solutions
- Pass an explicit ordered category list: `pd.Categorical(values, categories=[...], ordered=True)`.
- Drop or coerce unorderable values so the data is uniformly comparable before constructing.
- If ordering is not actually required, build with `ordered=False`.
Example fix
# before
pd.Categorical([{'a':1}, {'b':2}], ordered=True)
# after
pd.Categorical(['x','y'], categories=['x','y'], ordered=True) Defensive patterns
Strategy: validation
Validate before calling
def ordered_categorical(values, categories=None):
import pandas as pd
if categories is None:
try:
sorted(values)
except TypeError:
raise TypeError("values not sortable; supply explicit categories")
return pd.Categorical(values, categories=categories, ordered=True) Type guard
def is_sortable_iterable(values) -> bool:
try:
sorted(values)
return True
except TypeError:
return False Try / catch
try:
cat = pd.Categorical(values, ordered=True)
except TypeError as e:
if 'not ordered' in str(e):
cat = pd.Categorical(values, categories=explicit_order, ordered=True)
else:
raise Prevention
- Always pass explicit categories when requesting ordered=True for object data.
- Pre-clean heterogeneous values to a single comparable type.
- Prefer ordered=False unless a true total order exists.
When it happens
Trigger: `pd.Categorical(values, ordered=True)` where `values` contains unorderable objects (e.g. mixed types, dicts, uncomparable custom objects). The constructor falls back to unsorted factorize then re-raises this because ordered requires a total order.
Common situations: Building an ordered categorical from object-dtype data with heterogeneous contents; or from rows/dicts that have no natural `<` relation.
Related errors
- Unordered Categoricals can only compare equality or not
- Categoricals can only be compared if 'categories' are the sa
- Cannot compare a Categorical for op {opname} with type {type
- Categorical input must be list-like
- Cannot setitem on a Categorical with a new category ({fill_v
AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07).
Data as JSON: /api/errors/bc7a089d697d1846.
Report an issue: GitHub.