{"record":{"id":"52d3857574c3831e","repo":"pola-rs/polars","slug":"multi-dimensional-numpy-arrays-not-supported-as-in","errorCode":null,"errorMessage":"multi-dimensional NumPy arrays not supported as index","messagePattern":"multi-dimensional NumPy arrays not supported as index","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/_utils/getitem.py","lineNumber":241,"sourceCode":"        if key.is_empty():\n            return df.__class__()\n        dtype = key.dtype\n        if dtype == String:\n            return _select_columns_by_name(df, key)\n        elif dtype.is_integer():\n            return _select_columns_by_index(df, key)\n        elif dtype == Boolean:\n            return _select_columns_by_mask(df, key)\n        else:\n            msg = f\"cannot select columns using Series of type {dtype}\"\n            raise TypeError(msg)\n\n    elif _check_for_numpy(key) and isinstance(key, np.ndarray):\n        if key.ndim == 0:\n            key = np.atleast_1d(key)\n        elif key.ndim != 1:\n            msg = \"multi-dimensional NumPy arrays not supported as index\"\n            raise TypeError(msg)\n\n        if len(key) == 0:\n            return df.__class__()\n\n        dtype_kind = key.dtype.kind\n        if dtype_kind in (\"i\", \"u\"):\n            return _select_columns_by_index(df, key)\n        elif dtype_kind == \"b\":\n            return _select_columns_by_mask(df, key)\n        elif isinstance(key[0], str):\n            return _select_columns_by_name(df, key)\n        else:\n            msg = f\"cannot select columns using NumPy array of type {key.dtype}\"\n            raise TypeError(msg)\n\n    msg = (\n        f\"cannot select columns using key of type {qualified_type_name(key)!r}: {key!r}\"\n    )","sourceCodeStart":223,"sourceCodeEnd":259,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/_utils/getitem.py#L223-L259","documentation":"_select_columns accepts numpy arrays as column selectors only when they are 0-D or 1-D (dtype kinds i/u for indices, b for masks, U/S for names). Arrays with ndim >= 2 have no column-selection semantics, so polars raises TypeError immediately.","triggerScenarios":"df[np.array([[0, 1], [2, 3]])]; df[np.expand_dims(idx, 0)]; passing a (n, 1) reshaped index array; a 3-D boolean array from a computed mask.","commonSituations":"Reshaping index arrays with np.newaxis or .reshape(-1, 1) for sklearn-style pipelines then reusing them for dataframe indexing; broadcasting producing extra dimensions; batched masks stacked with np.stack.","solutions":["Flatten the array before indexing: df[key.ravel()] or df[key.flatten()].","Use key.squeeze() to drop singleton dimensions.","Convert to a 1-D list: df[list(key.ravel())].","Ensure masks/indices are computed as 1-D from the start (axis=0 reductions, keepdims=False).","Use df.select(...) with expressions instead of raw numpy arrays."],"exampleFix":"// before\ndf[np.array([[0, 2, 4]])]\n// after\ndf[np.array([[0, 2, 4]]).ravel()]","handlingStrategy":"validation","validationCode":"idx = np.asarray(selector)\nassert idx.ndim <= 1, f'expected 1-D selector, got ndim={idx.ndim}'\ndf[idx]","typeGuard":"def is_1d_array(key: object) -> bool:\n    import numpy as np\n    return isinstance(key, np.ndarray) and key.ndim == 1","tryCatchPattern":"try:\n    out = df[np_key]\nexcept TypeError as e:\n    if 'multi-dimensional' in str(e):\n        out = df[np.asarray(np_key).ravel()]\n    else:\n        raise","preventionTips":["Call .ravel()/.squeeze() on any array that may have gained dimensions (newaxis, stacking, sklearn reshapes).","Compute masks with keepdims=False and axis=0 reductions.","assert key.ndim == 1 before using arrays as dataframe selectors.","Convert to lists (key.tolist()) to sidestep shape rules entirely."],"tags":["polars","dataframe","numpy","array-shape"],"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"}