{"record":{"id":"5f84a4b62f5cebc3","repo":"pandas-dev/pandas","slug":"items-in-new-categories-are-not-the-same-as-in-old","errorCode":null,"errorMessage":"items in new_categories are not the same as in old categories","messagePattern":"items in new_categories are not the same as in old categories","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/categorical.py","lineNumber":1362,"sourceCode":"        3   a\n        dtype: category\n        Categories (3, str): ['c' < 'b' < 'a']\n\n        For :class:`pandas.CategoricalIndex`:\n\n        >>> ci = pd.CategoricalIndex([\"a\", \"b\", \"c\", \"a\"])\n        >>> ci\n        CategoricalIndex(['a', 'b', 'c', 'a'], categories=['a', 'b', 'c'],\n                         ordered=False, dtype='category')\n        >>> ci.reorder_categories([\"c\", \"b\", \"a\"], ordered=True)\n        CategoricalIndex(['a', 'b', 'c', 'a'], categories=['c', 'b', 'a'],\n                         ordered=True, dtype='category')\n        \"\"\"\n        if (\n            len(self.categories) != len(new_categories)\n            or not self.categories.difference(new_categories).empty\n        ):\n            raise ValueError(\n                \"items in new_categories are not the same as in old categories\"\n            )\n        return self.set_categories(new_categories, ordered=ordered)\n\n    def add_categories(self, new_categories) -> Self:\n        \"\"\"\n        Add new categories.\n\n        `new_categories` will be included at the last/highest place in the\n        categories and will be unused directly after this call.\n\n        Parameters\n        ----------\n        new_categories : category or list-like of category\n            The new categories to be included.\n\n        Returns\n        -------","sourceCodeStart":1344,"sourceCodeEnd":1380,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/categorical.py#L1344-L1380","documentation":"Raised by reorder_categories when the supplied new_categories differ in length or in members from the current categories. reorder_categories only permutes existing categories; it cannot add, drop, or rename them. The check uses both length equality and difference() to catch any deviation.","triggerScenarios":"`cat.reorder_categories(['b','a','d'])` where 'd' is not an existing category, or where one is missing, or where extra items are included.","commonSituations":"Confusing reorder with rename or set_categories; passing a reordered list that was built from a superset (e.g. all unique values rather than current categories).","solutions":["Pass exactly the current categories in the new order: `cat.reorder_categories(cat.categories[::-1])`.","To rename use `rename_categories(...)`; to change membership use `set_categories(...)`.","Verify `set(new_categories) == set(cat.categories)` before calling reorder_categories."],"exampleFix":"# before\ncat = pd.Categorical(['a','b','c'], categories=['a','b','c'])\ncat.reorder_categories(['c','b','a','d'])\n# after\ncat = pd.Categorical(['a','b','c'], categories=['a','b','c'])\ncat.reorder_categories(['c','b','a'])","handlingStrategy":"validation","validationCode":"def safe_reorder(cat, new_categories):\n    if set(new_categories) != set(cat.categories) or len(new_categories) != len(cat.categories):\n        raise ValueError(\"new_categories must be a permutation of current categories\")\n    return cat.reorder_categories(new_categories)","typeGuard":"def is_permutation_of_categories(cat, new_categories) -> bool:\n    return set(new_categories) == set(cat.categories) and len(new_categories) == len(cat.categories)","tryCatchPattern":"try:\n    cat = cat.reorder_categories(new_cats)\nexcept ValueError as e:\n    if 'not the same as in old categories' in str(e):\n        cat = cat.set_categories(new_cats)\n    else:\n        raise","preventionTips":["Use reorder_categories only for permutations; use set_categories otherwise.","Derive the new order from cat.categories to avoid drift.","Check set equality before reordering."],"tags":["categorical","reorder-categories","valueerror"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}