{"record":{"id":"d68e29b50fedbd7c","repo":"pola-rs/polars","slug":"cannot-parse-numpy-data-type-dtype-r-into-polars","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":330,"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":312,"sourceCodeEnd":348,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/datatypes/convert.py#L312-L348","documentation":"numpy_char_to_dtype maps a numpy dtype character code to a polars dtype using the (kind, itemsize) pair. String kinds 'U'/'S' map to String/Binary, but any other kind/itemsize combination missing from NUMPY_KIND_AND_ITEMSIZE_TO_DTYPE raises ValueError. The classic offender is float16 (kind 'f', itemsize 2), which polars has no dtype for.","triggerScenarios":"Converting arrays with dtype np.float16 or other unmapped (kind, itemsize) pairs through constructor helpers that resolve numpy character dtypes, e.g. pl.Series(model_output) where the array is half precision.","commonSituations":"Machine-learning pipelines: float16 activations/weights from PyTorch, ONNX, or TensorFlow; memory-saving half-precision columns read from disk; GPU-produced arrays.","solutions":["Cast before conversion: arr = arr.astype(np.float32) (or np.float64), then pl.Series(arr)","Convert half-precision data to float32 at load/export boundaries so float16 never reaches polars","If bit-exact storage matters, view the data as UInt16 and reinterpret later"],"exampleFix":"# before\ns = pl.Series(half_precision_array)  # ValueError: float16\n\n# after\ns = pl.Series(half_precision_array.astype(np.float32))","handlingStrategy":"validation","validationCode":"import numpy as np\n\ndef is_polars_mappable_dtype(arr: np.ndarray) -> bool:\n    d = arr.dtype\n    if d.kind in 'US':\n        return True\n    if d.kind == 'f' and d.itemsize < 4:\n        return False  # float16\n    if d.kind == 'c':\n        return False  # complex\n    return d.kind in 'biu'\n\nif not is_polars_mappable_dtype(arr):\n    arr = arr.astype(np.float32)","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.astype(np.float64))\n    else:\n        raise","preventionTips":["Cast float16 model outputs to float32 at export/load boundaries","Check arr.dtype.kind and itemsize for exotic arrays before handing them to polars"],"tags":["numpy","dtype","float16","conversion"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}