{"record":{"id":"d68e29b50fedbd7c","repo":"pola-rs/polars","slug":"cannot-parse-numpy-data-type-dtype-r-into-polars-data-type","errorCode":null,"errorMessage":"cannot parse numpy data type {dtype!r} into Polars data type","messagePattern":"cannot parse numpy data type (.+?) into Polars data type","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/datatypes/convert.py","lineNumber":339,"sourceCode":"        dtype.kind,\n        dtype.itemsize,\n    ) in DataTypeMappings.NUMPY_KIND_AND_ITEMSIZE_TO_DTYPE\n\n\ndef numpy_char_code_to_dtype(dtype_char: str) -> PolarsDataType:\n    \"\"\"Convert a numpy character dtype to a Polars dtype.\"\"\"\n    dtype = np.dtype(dtype_char)\n    if dtype.kind == \"U\":\n        return String\n    elif dtype.kind == \"S\":\n        return Binary\n    try:\n        return DataTypeMappings.NUMPY_KIND_AND_ITEMSIZE_TO_DTYPE[\n            dtype.kind, dtype.itemsize\n        ]\n    except KeyError:  # pragma: no cover\n        msg = f\"cannot parse numpy data type {dtype!r} into Polars data type\"\n        raise ValueError(msg) from None\n\n\ndef maybe_cast(el: Any, dtype: PolarsDataType) -> Any:\n    \"\"\"Try casting a value to a value that is valid for the given Polars dtype.\"\"\"\n    # cast el if it doesn't match\n    from polars._utils.convert import (\n        datetime_to_int,\n        timedelta_to_int,\n    )\n\n    time_unit: TimeUnit\n    if isinstance(el, datetime):\n        time_unit = getattr(dtype, \"time_unit\", \"us\")\n        return datetime_to_int(el, time_unit)\n    elif isinstance(el, timedelta):\n        time_unit = getattr(dtype, \"time_unit\", \"us\")\n        return timedelta_to_int(el, time_unit)\n","sourceCodeStart":321,"sourceCodeEnd":357,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/datatypes/convert.py#L321-L357","documentation":"numpy_char_code_to_dtype maps a numpy dtype (kind, itemsize) pair to a Polars dtype via NUMPY_KIND_AND_ITEMSIZE_TO_DTYPE; unsupported combinations raise ValueError. It handles the set of numpy dtypes polars can represent losslessly.","triggerScenarios":"Passing numpy arrays of kind 'U'/'S' with odd itemsizes, longdouble ('g'), complex ('c'), float16 ('f' itemsize 2), or >64-bit ints into pl.Series/from_numpy; __array_ufunc__ paths receiving such arrays.","commonSituations":"float16 arrays from ML preprocessing; complex arrays from signal processing; object arrays with untyped numpy dtype('O'); big-endian ('>i8') dtype variants on some versions.","solutions":["Cast the array first: arr.astype(np.float64) (or int64/uint64/datetime64[us]).","For float16: arr.astype(np.float32).","For strings/objects: convert to Python lists or let polars infer (pl.Series(arr.tolist()))."],"exampleFix":"// before\npl.Series(np.array([1.0, 2.0], dtype=np.float16))\n// after\narr = np.array([1.0, 2.0], dtype=np.float16).astype(np.float32)\npl.Series(arr)","handlingStrategy":"validation","validationCode":"OK_KINDS = {'b', 'i', 'u', 'f', 'm', 'M'}\ndef polars_compatible(arr: np.ndarray) -> bool:\n    k, itemsize = arr.dtype.kind, arr.dtype.itemsize\n    if k in 'iu' and itemsize <= 8: return True\n    if k == 'f' and itemsize in (4, 8): return True\n    if k == 'b': return True\n    if k in 'mM': return True\n    return False\n# if not polars_compatible(arr): arr = arr.astype(np.float64 or np.int64)","typeGuard":null,"tryCatchPattern":"try:\n    s = pl.Series(arr)\nexcept ValueError as e:\n    if \"cannot parse numpy data type\" in str(e):\n        s = pl.Series(arr.tolist())\n    else:\n        raise","preventionTips":["Cast float16/longdouble/complex/big-endian arrays to float64/int64 before polars","Convert 'U'/'S' string arrays to Python lists or utf-8 bytes","Normalize dtype endianness (arr.astype(arr.dtype.newbyteorder('=')))"],"tags":["python","numpy","polars","dtype"],"backgroundTag":"unsupported-dtype","analyzedSha":"fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e","analyzedAt":"2026-09-18T22:14:11.667Z","contentChangedAt":"2026-09-18T22:14:11.667Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}