pandas-dev/pandas · error · IndexError

Only integers, slices and integer or boolean arrays are vali

Error message

Only integers, slices and integer or boolean arrays are valid indices.

What it means

Raised by ArrowExtensionArray.__getitem__ when the indexer is a numpy array whose dtype kind is neither integer ('i','u') nor boolean ('b'). After check_array_indexer normalizes the input, only integer and boolean masks are valid; float or other-dtype ndarrays hit the final else. This mirrors numpy's indexing contract but gives a pandas-specific message.

Source

Thrown at pandas/core/arrays/arrow/array.py:894

            if not len(item):
                # Removable once we migrate StringDtype[pyarrow] to ArrowDtype[string]
                if (
                    isinstance(self._dtype, StringDtype)
                    and self._dtype.storage == "pyarrow"
                ):
                    # TODO(infer_string) should this be large_string?
                    pa_dtype = pa.string()
                else:
                    pa_dtype = self._dtype.pyarrow_dtype
                result = pa.chunked_array([], type=pa_dtype)
                return self._from_pyarrow_array(result)

            elif item.dtype.kind in "iu":
                return self.take(item)
            elif item.dtype.kind == "b":
                return self._from_pyarrow_array(self._pa_array.filter(item))
            else:
                raise IndexError(
                    "Only integers, slices and integer or "
                    "boolean arrays are valid indices."
                )
        elif isinstance(item, tuple):
            item = unpack_tuple_and_ellipses(item)

        if item is Ellipsis:
            # TODO: should be handled by pyarrow?
            item = slice(None)

        if is_scalar(item) and not is_integer(item):
            # e.g. "foo" or 2.5
            # exception message copied from numpy
            raise IndexError(
                r"only integers, slices (`:`), ellipsis (`...`), numpy.newaxis "
                r"(`None`) and integer or boolean arrays are valid indices"
            )
        # We are not an array indexer, so maybe e.g. a slice or integer

View on GitHub (pinned to 71959b8cb9)

Solutions

  1. Cast float indices to intp: s[np.asarray(idx, dtype=np.intp)].
  2. Ensure boolean masks stay bool: s[np.asarray(mask, dtype=bool)].
  3. Use .iloc / .loc and let pandas coerce, or use a list of ints: s[[1,2]].
  4. Recompute the index without float division: use // instead of /.

Example fix

# before
pos = (counts / 2)            # float64 ndarray
sub = s[pos]                  # IndexError
# after
pos = (counts // 2).astype(np.intp)
sub = s[pos]
Defensive patterns

Strategy: validation

Validate before calling

import numpy as np

def safe_arrow_index(arr, idx):
    if isinstance(idx, np.ndarray):
        if idx.dtype.kind == 'f':
            idx = idx.astype(np.intp)
        elif idx.dtype.kind not in ('i', 'u', 'b'):
            raise IndexError(f'unsupported index dtype {idx.dtype}')
    return arr[idx]

sub = safe_arrow_index(arrow_arr, positions)

Type guard

import numpy as np

def is_valid_arrow_index_array(idx) -> bool:
    return isinstance(idx, np.ndarray) and idx.dtype.kind in ('i', 'u', 'b')

Try / catch

try:
    sub = arrow_arr[idx]
except IndexError as e:
    if 'Only integers' in str(e) and hasattr(idx, 'astype'):
        sub = arrow_arr[np.asarray(idx, dtype=np.intp)]
    else:
        raise

Prevention

When it happens

Trigger: Indexing an ArrowExtensionArray/Series with a float numpy array: `s[np.array([1.0, 2.0])]`, `s[np.array([0.5, 1.5])]`, or a boolean-as-int8/uint8 mask whose kind is not 'b'. Also masked indexing where the mask came from arithmetic producing float dtype.

Common situations: Boolean masks accidentally upcast to float (e.g. `(s > 0) * 1.0`), computed indices from division yielding floats, JSON/CSV-loaded index arrays defaulting to float64, or passing a pandas Int8/UInt8 column (kind 'i'/'u' fine) vs Float (kind 'f' fails).

Related errors


AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07). Data as JSON: /api/errors/17ae9763550654af. Report an issue: GitHub.