pandas-dev/pandas · error · TypeError

index must be an integer, got

Error message

index must be an integer, got {type(index)}

What it means

The indexed form of ExtensionArray.item(index) validates that the supplied index is an integer via pandas' is_integer check. Passing a float, string, numpy float64, or any non-integral type raises TypeError because element access by position requires a concrete int. This guards against silent float->int truncation that numpy semantics would otherwise invite.

Solutions

  1. Coerce to int explicitly before calling: arr.item(int(idx)).
  2. Compute the index with integer division (//) instead of true division (/).
  3. If the index is symbolic, use arr.loc-style access on a wrapping Series instead of .item(name).

Example fix

// before
pos = len(arr) / 2
arr.item(pos)  # TypeError

// after
pos = len(arr) // 2
arr.item(int(pos))
Defensive patterns

Strategy: validation

Validate before calling

from pandas.api.types import is_integer
if not is_integer(index):
    raise TypeError(f'index must be int, got {type(index).__name__}')
_ = arr.item(int(index))

Type guard

def is_int_index(i) -> bool:
    from pandas.api.types import is_integer
    return is_integer(i)

Try / catch

try:
    val = arr.item(idx)
except TypeError:
    val = arr.item(int(idx))

Prevention

When it happens

Trigger: Calling arr.item(1.0), arr.item(np.float64(2)), arr.item('1'), or arr.item(np.int32(0)) on some platforms/configurations where the value is not recognized as a Python int. Also triggered by passing a value computed via division or averaging that is nominally integral but typed float.

Common situations: Index computed from len()/2 or an averaging expression yielding a float. Passing a numpy scalar whose kind is not recognized by is_integer. Pulling an index out of a dict/JSON as a string.

Related errors


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

Appendix: source

Thrown at pandas/core/arrays/base.py:683

        >>> arr = pd.array([1], dtype="Int64")
        >>> arr.item()
        np.int64(1)

        >>> arr = pd.array([1, 2, 3], dtype="Int64")
        >>> arr.item(0)
        np.int64(1)
        >>> arr.item(2)
        np.int64(3)
        """
        if index is None:
            if len(self) != 1:
                raise ValueError(
                    "can only convert an array of size 1 to a Python scalar"
                )
            return self[0]
        else:
            if not is_integer(index):
                raise TypeError(f"index must be an integer, got {type(index)}")
            return self[index]

    def to_numpy(
        self,
        dtype: npt.DTypeLike | None = None,
        copy: bool = False,
        na_value: object = lib.no_default,
    ) -> np.ndarray:
        """
        Convert to a NumPy ndarray.

        This is similar to :meth:`numpy.asarray`, but may provide additional control
        over how the conversion is done.

        Parameters
        ----------
        dtype : str or numpy.dtype, optional
            The dtype to pass to :meth:`numpy.asarray`.

View on GitHub (pinned to 3b7651241d)