pandas-dev/pandas · error · ValueError

invalid dtype specified {dtype}

Error message

invalid dtype specified {dtype}

What it means

Raised by NumericDtype._standardize_dtype when the supplied dtype does not map to any known masked numeric numpy dtype in the internal mapping (KeyError on the mapping lookup). Only the canonical masked numeric dtypes (Int8..Int64, UInt8..UInt64, Float32/Float64) are accepted.

Source

Thrown at pandas/core/arrays/numeric.py:124

    def _get_dtype_mapping(cls) -> Mapping[np.dtype, NumericDtype]:
        raise AbstractMethodError(cls)

    @classmethod
    def _standardize_dtype(cls, dtype: NumericDtype | str | np.dtype) -> NumericDtype:
        """
        Convert a string representation or a numpy dtype to NumericDtype.
        """
        if isinstance(dtype, str) and (dtype.startswith(("Int", "UInt", "Float"))):
            # Avoid DeprecationWarning from NumPy about np.dtype("Int64")
            # https://github.com/numpy/numpy/pull/7476
            dtype = dtype.lower()

        if not isinstance(dtype, NumericDtype):
            mapping = cls._get_dtype_mapping()
            try:
                dtype = mapping[np.dtype(dtype)]
            except KeyError as err:
                raise ValueError(f"invalid dtype specified {dtype}") from err
        return dtype

    @classmethod
    def _safe_cast(cls, values: np.ndarray, dtype: np.dtype, copy: bool) -> np.ndarray:
        """
        Safely cast the values to the given dtype.

        "safe" in this context means the casting is lossless.
        """
        raise AbstractMethodError(cls)


def _coerce_to_data_and_mask(values, dtype, copy: bool, dtype_cls: type[NumericDtype]):
    checker = dtype_cls._checker
    default_dtype = dtype_cls._default_np_dtype

    mask = None
    inferred_type = None

View on GitHub (pinned to 71959b8cb9)

Solutions

  1. Use a supported masked numeric dtype: 'Int8','Int16','Int32','Int64','UInt8'..'UInt64','Float32','Float64'.
  2. Check spelling/case: masked dtypes are capitalized (Int64 not int64 for the nullable variant).
  3. For plain numpy dtypes use the non-nullable path (dtype='int64').

Example fix

// before
pd.array([1, 2], dtype="Int128")  # raises: invalid dtype specified Int128

// after
pd.array([1, 2], dtype="Int64")
Defensive patterns

Strategy: validation

Validate before calling

SUPPORTED = {"Int8","Int16","Int32","Int64","UInt8","UInt16","UInt32","UInt64","Float32","Float64"}

def validate_dtype(dtype):
    name = getattr(dtype, "name", str(dtype))
    if name not in SUPPORTED:
        raise ValueError(f"unsupported masked numeric dtype: {dtype}")
    return dtype

Type guard

def is_supported_masked_numeric_dtype(dtype) -> bool:
    SUPPORTED = {"Int8","Int16","Int32","Int64","UInt8","UInt16","UInt32","UInt64","Float32","Float64"}
    return getattr(dtype, "name", str(dtype)) in SUPPORTED

Try / catch

try:
    arr = pd.array(vals, dtype=dtype)
except ValueError as e:
    if "invalid dtype specified" in str(e):
        arr = pd.array(vals, dtype="Int64")  # safe fallback
    else:
        raise

Prevention

When it happens

Trigger: Passing an unrecognized dtype string or numpy dtype such as pd.array(values, dtype='Int128'), dtype='S', dtype=complex, or any non-numeric masked dtype name to a masked numeric construction path.

Common situations: Typos in dtype strings ('itn64'); attempting to use a dtype pandas does not support as nullable numeric (complex, bytes); passing lowercase aliases that don't match the masked convention.

Related errors


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