pandas-dev/pandas · error · ValueError

codes need to be array-like integers

Error message

codes need to be array-like integers

What it means

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.

Solutions

  1. Cast codes to int before calling: `codes = pd.array(codes).astype('int64')` (only if no NaN).
  2. Validate `codes.dtype.kind in {'i', 'u'}` before passing.
  3. If codes originate as floats with NaN, fill NaN with -1 first, then cast to int64.
  4. Use the regular `pd.Categorical(values)` constructor if you actually have value labels rather than codes.

Example fix

# before
import pandas as pd
cat = pd.Categorical.from_codes([1.0, 0.0, 1.0], categories=['a', 'b'])  # ValueError

# after
cat = pd.Categorical.from_codes(
    pd.array([1.0, 0.0, 1.0]).astype('int64'),
    categories=['a', 'b'],
)
Defensive patterns

Strategy: validation

Validate before calling

import numpy as np

def to_int_codes(codes):
    arr = np.asarray(codes)
    if arr.dtype.kind not in 'iu':
        if arr.dtype.kind == 'f' and not np.isnan(arr).any():
            arr = arr.astype('int64')
        else:
            raise ValueError('codes must be integer-kind (or lossless float)')
    return arr

Type guard

def codes_are_integer_kind(codes) -> bool:
    import numpy as np
    arr = np.asarray(codes)
    return arr.dtype.kind in {'i', 'u'}

Try / catch

try:
    cat = pd.Categorical.from_codes(codes, categories=cats)
except ValueError as e:
    if 'array-like integers' in str(e):
        import numpy as np
        cat = pd.Categorical.from_codes(np.asarray(codes).astype('int64'), categories=cats)
    else:
        raise

Prevention

When it happens

Trigger: Passing `pd.Categorical.from_codes([1.0, 0.0], ...)` (float codes), `['0', '1']` (string codes), or a boolean array to `from_codes(..., validate=True)`.

Common situations: JSON/CSV deserialization where codes were serialized as floats/strings; loose typing from upstream calculators; user assumption that codes are coerced automatically.

Related errors


AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11). Data as JSON: /api/errors/abe0729786a3c792. Report an issue: GitHub.

Appendix: source

Thrown at pandas/core/arrays/categorical.py:1738

            fill_value = self._unbox_scalar(fill_value)
        else:
            raise TypeError(
                "Cannot setitem on a Categorical with a new "
                f"category ({fill_value}), set the categories first"
            ) from None
        return fill_value

    @classmethod
    def _validate_codes_for_dtype(cls, codes, *, dtype: CategoricalDtype) -> np.ndarray:
        if isinstance(codes, ExtensionArray) and is_integer_dtype(codes.dtype):
            # Avoid the implicit conversion of Int to object
            if isna(codes).any():
                raise ValueError("codes cannot contain NA values")
            codes = codes.to_numpy(dtype=np.int64)
        else:
            codes = np.asarray(codes)
        if len(codes) and codes.dtype.kind not in "iu":
            raise ValueError("codes need to be array-like integers")

        if len(codes) and (codes.max() >= len(dtype.categories) or codes.min() < -1):
            raise ValueError("codes need to be between -1 and len(categories)-1")
        return codes

    # -------------------------------------------------------------

    @ravel_compat
    def __array__(
        self, dtype: NpDtype | None = None, copy: bool | None = None
    ) -> np.ndarray:
        """
        The numpy array interface.

        Users should not call this directly. Rather, it is invoked by
        :func:`numpy.array` and :func:`numpy.asarray`.

        Parameters

View on GitHub (pinned to 3b7651241d)