{"record":{"id":"abe0729786a3c792","repo":"pandas-dev/pandas","slug":"codes-need-to-be-array-like-integers","errorCode":null,"errorMessage":"codes need to be array-like integers","messagePattern":"codes need to be array-like integers","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/categorical.py","lineNumber":1738,"sourceCode":"            fill_value = self._unbox_scalar(fill_value)\n        else:\n            raise TypeError(\n                \"Cannot setitem on a Categorical with a new \"\n                f\"category ({fill_value}), set the categories first\"\n            ) from None\n        return fill_value\n\n    @classmethod\n    def _validate_codes_for_dtype(cls, codes, *, dtype: CategoricalDtype) -> np.ndarray:\n        if isinstance(codes, ExtensionArray) and is_integer_dtype(codes.dtype):\n            # Avoid the implicit conversion of Int to object\n            if isna(codes).any():\n                raise ValueError(\"codes cannot contain NA values\")\n            codes = codes.to_numpy(dtype=np.int64)\n        else:\n            codes = np.asarray(codes)\n        if len(codes) and codes.dtype.kind not in \"iu\":\n            raise ValueError(\"codes need to be array-like integers\")\n\n        if len(codes) and (codes.max() >= len(dtype.categories) or codes.min() < -1):\n            raise ValueError(\"codes need to be between -1 and len(categories)-1\")\n        return codes\n\n    # -------------------------------------------------------------\n\n    @ravel_compat\n    def __array__(\n        self, dtype: NpDtype | None = None, copy: bool | None = None\n    ) -> np.ndarray:\n        \"\"\"\n        The numpy array interface.\n\n        Users should not call this directly. Rather, it is invoked by\n        :func:`numpy.array` and :func:`numpy.asarray`.\n\n        Parameters","sourceCodeStart":1720,"sourceCodeEnd":1756,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/categorical.py#L1720-L1756","documentation":"Raised by _validate_codes_for_dtype when the codes array, after conversion to a numpy array, has a dtype whose kind is not integer ('i' or 'u'). Codes must be integer positions into the categories array; float or object codes (e.g. [0.0, 1.0] or ['0','1']) are rejected.","triggerScenarios":"`pd.Categorical.from_codes([0.0, 1.0, 0.0], categories=['a','b'])` (float codes), or codes as strings. Only triggers when the array is non-empty; empty codes are allowed.","commonSituations":"Receiving codes from a JSON/CSV that parsed them as floats; downstream math that produced float arrays; mixing Int64 (handled above) vs plain float.","solutions":["Cast codes to int first: `pd.Categorical.from_codes(np.asarray(codes).astype(np.int64), categories=[...])`.","Ensure the source produces integer dtype (e.g. `.astype('int64')` after rounding/filling NA).","If codes are non-integer labels, use the regular `pd.Categorical(values)` constructor instead of from_codes."],"exampleFix":"# before\npd.Categorical.from_codes([0.0, 1.0, 0.0], categories=['a','b'])\n# after\nimport numpy as np\npd.Categorical.from_codes(np.asarray([0.0, 1.0, 0.0]).astype(np.int64), categories=['a','b'])","handlingStrategy":"validation","validationCode":"import numpy as np\n\ndef to_int_codes(codes):\n    arr = np.asarray(codes)\n    if arr.dtype.kind not in 'iu':\n        arr = arr.astype(np.int64)\n    return arr\n\n# usage: pd.Categorical.from_codes(to_int_codes(codes), categories=cats)","typeGuard":"def is_integer_codes(codes) -> bool:\n    import numpy as np\n    arr = np.asarray(codes)\n    return arr.dtype.kind in 'iu'","tryCatchPattern":"try:\n    cat = pd.Categorical.from_codes(codes, categories=cats)\nexcept ValueError as e:\n    if 'array-like integers' in str(e):\n        import numpy as np\n        cat = pd.Categorical.from_codes(np.asarray(codes).astype(np.int64), categories=cats)\n    else:\n        raise","preventionTips":["Cast codes to int64 before passing to from_codes.","Round floats then cast if codes arrived as floats.","Use the regular constructor if your input is labels, not integer positions."],"tags":["categorical","from-codes","integer-codes","dtype","valueerror"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}