{"record":{"id":"2ef99fea64b49370","repo":"pola-rs/polars","slug":"only-1d-numpy-arrays-can-be-treated-as-indices","errorCode":null,"errorMessage":"only 1D NumPy arrays can be treated as indices","messagePattern":"only 1D NumPy arrays can be treated as indices","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/_utils/getitem.py","lineNumber":412,"sourceCode":"\n    return s.cast(idx_type)\n\n\ndef _convert_np_ndarray_to_indices(arr: np.ndarray[Any, Any], size: int) -> Series:\n    \"\"\"Convert a NumPy ndarray to indices, taking into account negative values.\"\"\"\n    # Unsigned or signed Numpy array (ordered from fastest to slowest).\n    #   - np.uint32 (polars) or np.uint64 (polars_u64_idx) numpy array\n    #     indexes.\n    #   - Other unsigned numpy array indexes are converted to pl.UInt32\n    #     (polars) or pl.UInt64 (polars_u64_idx).\n    #   - Signed numpy array indexes are converted pl.UInt32 (polars) or\n    #     pl.UInt64 (polars_u64_idx) after negative indexes are converted\n    #     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)","sourceCodeStart":394,"sourceCodeEnd":430,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/_utils/getitem.py#L394-L430","documentation":"_convert_np_ndarray_to_indices (getitem.py:412) requires numpy index arrays to be 1D; 0-D arrays are promoted with np.atleast_1d, but arrays with ndim > 1 are ambiguous as row indices and raise this TypeError immediately (before dtype checks).","triggerScenarios":"df[np.array([[0, 1], [2, 3]])]; s[two_d_bool_or_int_array]; results of np.where() on a 2D matrix; index arrays shaped (n, 1) from reshaping/slicing.","commonSituations":"np.argmin/np.where over matrices producing 2D results; column vectors from sklearn-style pipelines; forgetting to flatten batched index outputs.","solutions":["Flatten before indexing: df[arr.ravel()] or df[arr.reshape(-1)]","For (n, 1) arrays squeeze the trailing axis: df[arr.squeeze(-1)]","If you meant element-wise 2D gather, iterate columns explicitly instead of passing the 2D array"],"exampleFix":"# before\ndf[np.array([[0, 2], [4, 6]])]\n\n# after\ndf[np.array([[0, 2], [4, 6]]).ravel()]","handlingStrategy":"type-guard","validationCode":"import numpy as np\n\nif arr.ndim != 1:\n    arr = np.atleast_1d(arr.squeeze()) if arr.ndim == 2 and 1 in arr.shape else arr.ravel()\nassert arr.ndim == 1\ndf[arr]","typeGuard":"import numpy as np\n\ndef is_1d_index_array(arr) -> bool:\n    return isinstance(arr, np.ndarray) and arr.ndim == 1","tryCatchPattern":null,"preventionTips":["Call .ravel()/.flatten() on matrix-shaped results before indexing","squeeze() column vectors shaped (n, 1)","Log arr.shape next to index errors to catch dimension bugs early"],"tags":["python","polars","numpy","indices","shape","typeerror"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}