pandas-dev/pandas · error · TypeError

Cannot cast {type(self).__name__} to dtype {dtype}

Error message

Cannot cast {type(self).__name__} to dtype {dtype}

What it means

Raised as a TypeError by `IntervalArray.astype` when casting to a non-IntervalDtype target fails inside the base `ExtensionArray.astype`. Common when the target dtype cannot hold interval data (e.g., a plain numeric dtype, bool, or unsupported object form). Fires at pandas/core/arrays/interval.py:971.

Source

Thrown at pandas/core/arrays/interval.py:971

                new_left = Index(self._left, copy=False).astype(dtype.subtype)
                new_right = Index(self._right, copy=False).astype(dtype.subtype)
            except IntCastingNaNError:
                # e.g test_subtype_integer
                raise
            except (TypeError, ValueError) as err:
                # e.g. test_subtype_integer_errors f8->u8 can be lossy
                #  and raises ValueError
                msg = (
                    f"Cannot convert {self.dtype} to {dtype}; subtypes are incompatible"
                )
                raise TypeError(msg) from err
            return self._shallow_copy(new_left, new_right)
        else:
            try:
                return super().astype(dtype, copy=copy)
            except (TypeError, ValueError) as err:
                msg = f"Cannot cast {type(self).__name__} to dtype {dtype}"
                raise TypeError(msg) from err

    def equals(self, other) -> bool:
        if type(self) != type(other):
            return False

        return bool(
            self.closed == other.closed
            and self.left.equals(other.left)
            and self.right.equals(other.right)
        )

    @classmethod
    def _concat_same_type(cls, to_concat: Sequence[IntervalArray]) -> Self:
        """
        Concatenate multiple IntervalArray

        Parameters
        ----------

View on GitHub (pinned to 71959b8cb9)

Solutions

  1. Extract a component first: `ia.left.astype('int64')` for the lower bound, or `ia.astype('object')` to get an object array of Interval scalars.
  2. Use `np.asarray(ia, dtype=object)` to materialize Interval objects.
  3. For tuples: build via `list(zip(ia.left, ia.right))`.

Example fix

// before
ia.astype('int64')
// after
ia.left.astype('int64')  # lower bounds
# or
np.asarray(ia, dtype=object)  # array of Interval scalars
Defensive patterns

Strategy: type-guard

Validate before calling

import numpy as np
import pandas as pd

def interval_to_target(ia, dtype):
    if dtype in ('int64','float64','int32','uint64'):
        return ia.left.astype(dtype)  # or build (left, right) pair
    if dtype in (object, 'object'):
        return np.asarray(ia, dtype=object)
    return ia.astype(dtype)

Type guard

import pandas as pd

def is_interval_compatible_dtype(dtype) -> bool:
    return isinstance(dtype, pd.IntervalDtype) or (isinstance(dtype, str) and dtype.startswith('interval'))

Try / catch

try:
    out = ia.astype(dtype)
except TypeError as e:
    if "Cannot cast" in str(e) and "IntervalArray" in str(e):
        out = np.asarray(ia, dtype=object)
    else:
        raise

Prevention

When it happens

Trigger: `ia.astype('int64')`, `ia.astype(bool)`, or `ia.astype(str)` directly on an IntervalArray.

Common situations: Trying to flatten intervals into numeric codes for ML pipelines, or coercing to object for serialization.

Related errors


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