{"record":{"id":"79592b29a443e920","repo":"pola-rs/polars","slug":"cannot-treat-numpy-array-of-type-arr-dtype-as-in","errorCode":null,"errorMessage":"cannot treat NumPy array of type {arr.dtype} as indices","messagePattern":"cannot treat NumPy array of type (.+?) as indices","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/_utils/getitem.py","lineNumber":425,"sourceCode":"    #     to absolute indexes.\n    if arr.ndim == 0:\n        arr = np.atleast_1d(arr)\n    if arr.ndim != 1:\n        msg = \"only 1D NumPy arrays can be treated as indices\"\n        raise TypeError(msg)\n\n    idx_type = get_index_type()\n\n    if len(arr) == 0:\n        return pl.Series(\"\", [], dtype=idx_type)\n\n    # Numpy array with signed or unsigned integers.\n    if arr.dtype.kind not in (\"i\", \"u\"):\n        if arr.dtype.kind == \"b\":\n            _raise_on_boolean_mask()\n        else:\n            msg = f\"cannot treat NumPy array of type {arr.dtype} as indices\"\n            raise TypeError(msg)\n\n    if idx_type == UInt32:\n        if arr.dtype in {np.int64, np.uint64} and arr.max() >= U32_MAX:\n            msg = \"index positions should be smaller than 2^32\"\n            raise ValueError(msg)\n        if arr.dtype == np.int64 and arr.min() < -U32_MAX:\n            msg = \"index positions should be greater than or equal to -2^32\"\n            raise ValueError(msg)\n\n    if arr.dtype.kind == \"i\" and arr.min() < 0:\n        if idx_type == UInt32:\n            if arr.dtype in (np.int8, np.int16):\n                arr = arr.astype(np.int32)\n        else:\n            if arr.dtype in (np.int8, np.int16, np.int32):\n                arr = arr.astype(np.int64)\n\n        # Update negative indexes to absolute indexes.","sourceCodeStart":407,"sourceCodeEnd":443,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/_utils/getitem.py#L407-L443","documentation":"In _convert_np_ndarray_to_indices (getitem.py:425), numpy index arrays must have integer dtype (kind 'i' or 'u'); boolean arrays route to the boolean-mask error, and every other dtype — float, str, datetime64, object — raises this TypeError naming arr.dtype.","triggerScenarios":"df[np.array([0.5, 1.5])] (floats from division or np.mean); df[np.array(['a', 'b'])]; df[np.array(['2024-01-01'], dtype='datetime64[ns]')]; df[np.array([1, 2], dtype=object)] from pandas .to_numpy() on mixed columns.","commonSituations":"numpy operations that upcast indices to float (e.g. np.isnan-affected arrays, division); converting pandas object columns to positions; string keys mistakenly used as positions.","solutions":["Cast to integer dtype: df[arr.astype(np.int64)] (floor/round first if fractional)","For value-based matching use df.filter(pl.col('c').is_in(arr.tolist()))","Ensure index-producing numpy ops stay integral (e.g. use np.flatnonzero instead of manual float math)"],"exampleFix":"# before\ndf[np.array([0.5, 1.5])]\n\n# after\ndf[np.array([0.5, 1.5]).round().astype(np.int64)]","handlingStrategy":"type-guard","validationCode":"import numpy as np\n\nif arr.dtype.kind not in (\"i\", \"u\"):\n    if arr.dtype.kind == \"b\":\n        arr = np.flatnonzero(arr)  # or use df.filter(mask)\n    else:\n        arr = arr.astype(np.int64)\ndf[arr]","typeGuard":"import numpy as np\n\ndef is_integer_index_array(arr) -> bool:\n    return isinstance(arr, np.ndarray) and arr.ndim == 1 and arr.dtype.kind in (\"i\", \"u\")","tryCatchPattern":null,"preventionTips":["Cast float index arrays with .astype(np.int64) after rounding","Watch for object dtype when converting from pandas; use .astype(np.int64) explicitly","Use df.filter(...is_in(...)) for value matching rather than string arrays"],"tags":["python","polars","numpy","indices","dtype","typeerror"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}