{"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":null,"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/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/_utils/getitem.py#L394-L430","documentation":"`_convert_np_ndarray_to_indices` only accepts 1-D NumPy arrays as row index selectors. After promoting 0-D arrays via `np.atleast_1d`, any array with ndim != 1 (2-D matrix, etc.) raises TypeError because a multi-dimensional array has no single positional meaning per row.","triggerScenarios":"Passing a 2-D NumPy array to `s[np_arr]` or `df[np_arr]`, e.g. `s[np.array([[0, 1], [2, 3]])]` or the result of a vectorized computation that added a dimension.","commonSituations":"NumPy broadcasting/expanding an index array (`np.newaxis`, stacking, `np.meshgrid` output), or passing `df.to_numpy()` output back as an index.","solutions":["Flatten with `.ravel()` or select one column before indexing: `s[arr.ravel()]`.","If you meant multiple independent index vectors, loop or use `np.concatenate`.","Verify `arr.ndim == 1` before indexing."],"exampleFix":"// before\narr = np.array([[0, 1], [2, 3]])\nsub = s[arr]  # TypeError: only 1D NumPy arrays...\n// after\nsub = s[arr.ravel()]","handlingStrategy":"type-guard","validationCode":"import numpy as np\nif isinstance(idx, np.ndarray) and idx.ndim != 1:\n    idx = idx.ravel()","typeGuard":"def is_1d_int_array(x) -> bool:\n    return isinstance(x, np.ndarray) and x.ndim == 1 and x.dtype.kind in ('i', 'u')","tryCatchPattern":"try:\n    sub = s[np_idx]\nexcept TypeError as e:\n    if \"only 1D NumPy arrays\" in str(e):\n        sub = s[np.asarray(np_idx).ravel()]\n    else:\n        raise","preventionTips":["Check `arr.ndim == 1` before using arrays as indices.","Beware broadcasting/`np.newaxis` adding dims to index arrays.","Never pass `df.to_numpy()` output directly as an index."],"tags":["polars","numpy","indexing","typeerror"],"backgroundTag":"shape-mismatch","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"}