{"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/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/categorical.py#L467-L503","documentation":"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.","triggerScenarios":"`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.","commonSituations":"Building an ordered categorical from object-dtype data with heterogeneous contents; or from rows/dicts that have no natural `<` relation.","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`."],"exampleFix":"# before\npd.Categorical([{'a':1}, {'b':2}], ordered=True)\n# after\npd.Categorical(['x','y'], categories=['x','y'], ordered=True)","handlingStrategy":"validation","validationCode":"def ordered_categorical(values, categories=None):\n    import pandas as pd\n    if categories is None:\n        try:\n            sorted(values)\n        except TypeError:\n            raise TypeError(\"values not sortable; supply explicit categories\")\n    return pd.Categorical(values, categories=categories, ordered=True)","typeGuard":"def is_sortable_iterable(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 'not ordered' in str(e):\n        cat = pd.Categorical(values, categories=explicit_order, ordered=True)\n    else:\n        raise","preventionTips":["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."],"tags":["categorical","ordered","factorize","unsortable","typeerror"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}