pola-rs/polars · error

multi-dimensional NumPy arrays not supported as index

Error message

multi-dimensional NumPy arrays not supported as index

What it means

_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.

Solutions

  1. Flatten the array before indexing: df[key.ravel()] or df[key.flatten()].
  2. Use key.squeeze() to drop singleton dimensions.
  3. Convert to a 1-D list: df[list(key.ravel())].
  4. Ensure masks/indices are computed as 1-D from the start (axis=0 reductions, keepdims=False).
  5. Use df.select(...) with expressions instead of raw numpy arrays.

Example fix

// before
df[np.array([[0, 2, 4]])]
// after
df[np.array([[0, 2, 4]]).ravel()]
Defensive patterns

Strategy: validation

Validate before calling

idx = np.asarray(selector)
assert idx.ndim <= 1, f'expected 1-D selector, got ndim={idx.ndim}'
df[idx]

Type guard

def is_1d_array(key: object) -> bool:
    import numpy as np
    return isinstance(key, np.ndarray) and key.ndim == 1

Try / catch

try:
    out = df[np_key]
except TypeError as e:
    if 'multi-dimensional' in str(e):
        out = df[np.asarray(np_key).ravel()]
    else:
        raise

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18). Data as JSON: /api/errors/52d3857574c3831e. Report an issue: GitHub.

Appendix: source

Thrown at py-polars/src/polars/_utils/getitem.py:241

        if key.is_empty():
            return df.__class__()
        dtype = key.dtype
        if dtype == String:
            return _select_columns_by_name(df, key)
        elif dtype.is_integer():
            return _select_columns_by_index(df, key)
        elif dtype == Boolean:
            return _select_columns_by_mask(df, key)
        else:
            msg = f"cannot select columns using Series of type {dtype}"
            raise TypeError(msg)

    elif _check_for_numpy(key) and isinstance(key, np.ndarray):
        if key.ndim == 0:
            key = np.atleast_1d(key)
        elif key.ndim != 1:
            msg = "multi-dimensional NumPy arrays not supported as index"
            raise TypeError(msg)

        if len(key) == 0:
            return df.__class__()

        dtype_kind = key.dtype.kind
        if dtype_kind in ("i", "u"):
            return _select_columns_by_index(df, key)
        elif dtype_kind == "b":
            return _select_columns_by_mask(df, key)
        elif isinstance(key[0], str):
            return _select_columns_by_name(df, key)
        else:
            msg = f"cannot select columns using NumPy array of type {key.dtype}"
            raise TypeError(msg)

    msg = (
        f"cannot select columns using key of type {qualified_type_name(key)!r}: {key!r}"
    )

View on GitHub (pinned to fe841f959e)