{"record":{"id":"c68e9fd7614d15b5","repo":"pandas-dev/pandas","slug":"cannot-cast-type-self-name-to-dtype-dtype-c68e9f","errorCode":null,"errorMessage":"Cannot cast {type(self).__name__} to dtype {dtype}","messagePattern":"Cannot cast (.+?) to dtype (.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/interval.py","lineNumber":971,"sourceCode":"                new_left = Index(self._left, copy=False).astype(dtype.subtype)\n                new_right = Index(self._right, copy=False).astype(dtype.subtype)\n            except IntCastingNaNError:\n                # e.g test_subtype_integer\n                raise\n            except (TypeError, ValueError) as err:\n                # e.g. test_subtype_integer_errors f8->u8 can be lossy\n                #  and raises ValueError\n                msg = (\n                    f\"Cannot convert {self.dtype} to {dtype}; subtypes are incompatible\"\n                )\n                raise TypeError(msg) from err\n            return self._shallow_copy(new_left, new_right)\n        else:\n            try:\n                return super().astype(dtype, copy=copy)\n            except (TypeError, ValueError) as err:\n                msg = f\"Cannot cast {type(self).__name__} to dtype {dtype}\"\n                raise TypeError(msg) from err\n\n    def equals(self, other) -> bool:\n        if type(self) != type(other):\n            return False\n\n        return bool(\n            self.closed == other.closed\n            and self.left.equals(other.left)\n            and self.right.equals(other.right)\n        )\n\n    @classmethod\n    def _concat_same_type(cls, to_concat: Sequence[IntervalArray]) -> Self:\n        \"\"\"\n        Concatenate multiple IntervalArray\n\n        Parameters\n        ----------","sourceCodeStart":953,"sourceCodeEnd":989,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/interval.py#L953-L989","documentation":"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.","triggerScenarios":"`ia.astype('int64')`, `ia.astype(bool)`, or `ia.astype(str)` directly on an IntervalArray.","commonSituations":"Trying to flatten intervals into numeric codes for ML pipelines, or coercing to object for serialization.","solutions":["Extract a component first: `ia.left.astype('int64')` for the lower bound, or `ia.astype('object')` to get an object array of Interval scalars.","Use `np.asarray(ia, dtype=object)` to materialize Interval objects.","For tuples: build via `list(zip(ia.left, ia.right))`."],"exampleFix":"// before\nia.astype('int64')\n// after\nia.left.astype('int64')  # lower bounds\n# or\nnp.asarray(ia, dtype=object)  # array of Interval scalars","handlingStrategy":"type-guard","validationCode":"import numpy as np\nimport pandas as pd\n\ndef interval_to_target(ia, dtype):\n    if dtype in ('int64','float64','int32','uint64'):\n        return ia.left.astype(dtype)  # or build (left, right) pair\n    if dtype in (object, 'object'):\n        return np.asarray(ia, dtype=object)\n    return ia.astype(dtype)","typeGuard":"import pandas as pd\n\ndef is_interval_compatible_dtype(dtype) -> bool:\n    return isinstance(dtype, pd.IntervalDtype) or (isinstance(dtype, str) and dtype.startswith('interval'))","tryCatchPattern":"try:\n    out = ia.astype(dtype)\nexcept TypeError as e:\n    if \"Cannot cast\" in str(e) and \"IntervalArray\" in str(e):\n        out = np.asarray(ia, dtype=object)\n    else:\n        raise","preventionTips":["Use ia.left / ia.right for numeric extraction instead of ia.astype(int).","Use np.asarray(ia, dtype=object) to get Interval scalars.","Reserve ia.astype for interval-to-interval subtype changes."],"tags":["interval","astype","casting","dtype"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}