{"record":{"id":"bc7a089d697d1846","repo":"pandas-dev/pandas","slug":"values-is-not-ordered-please-explicitly-specify","errorCode":null,"errorMessage":"'values' is not ordered, please explicitly specify the categories order by passing in a categories argument.","messagePattern":"'values' is not ordered, please explicitly specify the categories order by passing in a categories argument\\.","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/categorical.py","lineNumber":485,"sourceCode":"                categories = arr.dictionary.to_pandas(types_mapper=ArrowDtype)\n                codes = arr.indices.to_numpy()\n                dtype = CategoricalDtype(categories, values.dtype.pyarrow_dtype.ordered)\n            else:\n                preserve_object = False\n                if isinstance(values, (ABCIndex, ABCSeries)) and values.dtype == object:\n                    # GH#61778\n                    preserve_object = True\n                if not isinstance(values, ABCIndex):\n                    # in particular RangeIndex xref test_index_equal_range_categories\n                    values = sanitize_array(values, None)\n                try:\n                    codes, categories = factorize(values, sort=True)\n                except TypeError as err:\n                    codes, categories = factorize(values, sort=False)\n                    if dtype.ordered:\n                        # raise, as we don't have a sortable data structure and so\n                        # the user should give us one by specifying categories\n                        raise TypeError(\n                            \"'values' is not ordered, please \"\n                            \"explicitly specify the categories order \"\n                            \"by passing in a categories argument.\"\n                        ) from err\n\n                if preserve_object:\n                    # GH#61778 wrap categories in an Index to prevent dtype\n                    #  inference in the CategoricalDtype constructor\n                    from pandas import Index\n\n                    categories = Index(categories, dtype=object, copy=False)\n\n                # if not preserve_object, we're inferring from values\n                dtype = CategoricalDtype(categories, dtype.ordered)\n\n        elif isinstance(values.dtype, CategoricalDtype):\n            old_codes = extract_array(values)._codes\n            codes = recode_for_categories(","sourceCodeStart":467,"sourceCodeEnd":503,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/categorical.py#L467-L503","documentation":"Raised during category inference in `__init__` when `dtype.ordered=True` but `factorize(values, sort=True)` raised `TypeError` (the values are not sortable, e.g. mixed incompatible types) and the fallback `factorize(sort=False)` succeeded. Because an ordered categorical requires a well-defined sort order, pandas asks the caller to supply an explicit `categories` sequence defining that order.","triggerScenarios":"Constructing `pd.Categorical(values, ordered=True)` where `values` contains heterogeneous/unorderable types (e.g. `['a', 1, None]`), or unorderable objects whose `__lt__` raises.","commonSituations":"Loading messy CSV columns with mixed dtypes; building ordered categoricals from object columns that contain a few stray numeric/None entries; user-defined classes without a total order.","solutions":["Provide an explicit ordered category list: `pd.Categorical(values, categories=[...], ordered=True)`.","Clean/coerce the values to a single sortable dtype before construction.","Drop `ordered=True` if a total order is not actually required.","Pre-sort the unique values yourself and pass them as `categories`."],"exampleFix":"# before\nimport pandas as pd\ncat = pd.Categorical(['a', 1, 'b'], ordered=True)  # TypeError\n\n# after\ncat = pd.Categorical(\n    ['a', 1, 'b'],\n    categories=['a', 'b', 1],  # explicit order\n    ordered=True,\n)","handlingStrategy":"validation","validationCode":"def ordered_categorical(values, categories=None):\n    if categories is None:\n        import pandas as pd\n        uniq = pd.unique([v for v in values if v is not None])\n        try:\n            uniq = sorted(uniq)\n        except TypeError as e:\n            raise TypeError(\n                'values are not sortable; pass categories= explicitly'\n            ) from e\n        categories = uniq\n    return pd.Categorical(values, categories=categories, ordered=True)","typeGuard":"def is_sortable(values) -> bool:\n    try:\n        sorted(values)\n        return True\n    except TypeError:\n        return False","tryCatchPattern":"try:\n    cat = pd.Categorical(values, ordered=True)\nexcept TypeError as e:\n    if 'is not ordered' in str(e):\n        cat = pd.Categorical(values, categories=sorted(set(values)), ordered=True)\n    else:\n        raise","preventionTips":["Always pass `categories=[...]` when constructing an ordered Categorical from untrusted/mixed-type data.","Coerce the values to a single sortable dtype before construction.","Drop `ordered=True` if you do not actually need a total order."],"tags":["categorical","constructor","ordered","factorize","typeerror"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}