{"record":{"id":"32e1401cb2e9e03c","repo":"pandas-dev/pandas","slug":"cannot-set-a-categorical-with-another-without-ide","errorCode":null,"errorMessage":"Cannot set a Categorical with another, without identical categories","messagePattern":"Cannot set a Categorical with another, without identical categories","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/categorical.py","lineNumber":2465,"sourceCode":"            result = f\"{body}\\n{footer}\"\n        else:\n            # In the empty case we use a comma instead of newline to get\n            #  a more compact __repr__\n            body = \"[]\"\n            result = f\"{body}, {footer}\"\n\n        return result\n\n    # ------------------------------------------------------------------\n\n    def _validate_listlike(self, value):\n        # NB: here we assume scalar-like tuples have already been excluded\n        value = extract_array(value, extract_numpy=True)\n\n        # require identical categories set\n        if isinstance(value, Categorical):\n            if self.dtype != value.dtype:\n                raise TypeError(\n                    \"Cannot set a Categorical with another, \"\n                    \"without identical categories\"\n                )\n            # dtype equality implies categories_match_up_to_permutation\n            value = self._encode_with_my_categories(value)\n            return value._codes\n\n        from pandas import Index\n\n        # tupleize_cols=False for e.g. test_fillna_iterable_category GH#41914\n        to_add = Index._with_infer(value, tupleize_cols=False, copy=False).difference(\n            self.categories\n        )\n\n        # no assignments of values not in categories, but it's always ok to set\n        # something to np.nan\n        if len(to_add) and not isna(to_add).all():\n            raise TypeError(","sourceCodeStart":2447,"sourceCodeEnd":2483,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/categorical.py#L2447-L2483","documentation":"Raised by Categorical._validate_listlike when assigning one Categorical into another whose categories (set or ordering) differ, i.e. self.dtype != value.dtype. Categorical assignment requires the two dtype signatures (categories AND ordered flag) to be identical so codes map consistently. If they differ only by permutation pandas can re-encode, but a full dtype mismatch is rejected here.","triggerScenarios":"df['a'] = other_cat where df['a'] is a category column and other_cat has different categories; setitem on a categorical Series/Index with a Categorical whose categories differ; fillna with a Categorical of a different category set.","commonSituations":"Joining or assigning between two DataFrames whose 'category' columns were built independently (different categories inferred from different data slices), or after refiltering where unseen categories were dropped. Also common after pd.concat then reassigning slices.","solutions":["Unify categories first: target.cat.set_categories(other.cat.categories, ordered=other.cat.ordered) on one side.","Use union_categoricals([a, b]) to build a shared category set before assignment.","Cast both sides to a common non-categorical dtype (e.g. .astype(str)) if category alignment is not needed."],"exampleFix":"// before\ns = pd.Series(pd.Categorical(['a','b'], categories=['a','b']))\ns[:] = pd.Categorical(['x','y'], categories=['x','y'])  # TypeError\n\n// after\ns = s.cat.set_categories(['x','y','a','b'])\ns[:] = pd.Categorical(['x','y'], categories=['x','y','a','b'])","handlingStrategy":"validation","validationCode":"def compatible_assign(target, value):\n    import pandas as pd\n    if isinstance(value.dtype, pd.CategoricalDtype) and target.dtype != value.dtype:\n        return target.cat.set_categories(value.cat.categories, ordered=value.cat.ordered)\n    return target","typeGuard":"import pandas as pd\nfrom typing import Any\n\ndef categories_match(a: Any, b: Any) -> bool:\n    da, db = getattr(a, 'dtype', None), getattr(b, 'dtype', None)\n    if not (isinstance(da, pd.CategoricalDtype) and isinstance(db, pd.CategoricalDtype)):\n        return True\n    return da == db","tryCatchPattern":"try:\n    target[:] = value\nexcept TypeError as e:\n    if 'without identical categories' in str(e):\n        target = target.cat.set_categories(value.cat.categories, ordered=value.cat.ordered)\n        target[:] = value\n    else:\n        raise","preventionTips":["Use union_categoricals to establish a shared category set before assignment.","Build category columns from a single canonical category definition."],"tags":["categorical","setitem","categories"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}