{"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/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/categorical.py#L1720-L1756","documentation":"Raised by `_validate_codes_for_dtype` when the `codes` array, after coercion, does not have an integer dtype kind (`'i'` or `'u'`). Categorical codes must be integers because they index into the categories array; float, object, or string codes have no valid meaning and are rejected.","triggerScenarios":"Passing `pd.Categorical.from_codes([1.0, 0.0], ...)` (float codes), `['0', '1']` (string codes), or a boolean array to `from_codes(..., validate=True)`.","commonSituations":"JSON/CSV deserialization where codes were serialized as floats/strings; loose typing from upstream calculators; user assumption that codes are coerced automatically.","solutions":["Cast codes to int before calling: `codes = pd.array(codes).astype('int64')` (only if no NaN).","Validate `codes.dtype.kind in {'i', 'u'}` before passing.","If codes originate as floats with NaN, fill NaN with -1 first, then cast to int64.","Use the regular `pd.Categorical(values)` constructor if you actually have value labels rather than codes."],"exampleFix":"# before\nimport pandas as pd\ncat = pd.Categorical.from_codes([1.0, 0.0, 1.0], categories=['a', 'b'])  # ValueError\n\n# after\ncat = pd.Categorical.from_codes(\n    pd.array([1.0, 0.0, 1.0]).astype('int64'),\n    categories=['a', 'b'],\n)","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        if arr.dtype.kind == 'f' and not np.isnan(arr).any():\n            arr = arr.astype('int64')\n        else:\n            raise ValueError('codes must be integer-kind (or lossless float)')\n    return arr","typeGuard":"def codes_are_integer_kind(codes) -> bool:\n    import numpy as np\n    arr = np.asarray(codes)\n    return arr.dtype.kind in {'i', 'u'}","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('int64'), categories=cats)\n    else:\n        raise","preventionTips":["Cast codes to `int64` before passing to `from_codes`.","Validate `np.asarray(codes).dtype.kind in {'i','u'}` at the boundary.","If the values are actually labels, use `pd.Categorical(values)` instead of `from_codes`."],"tags":["categorical","from-codes","codes","dtype","valueerror"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}