pola-rs/polars · error · TypeError

multi-dimensional NumPy arrays not supported as index

Error message

multi-dimensional NumPy arrays not supported as index

What it means

DataFrame.__getitem__ with a NumPy array first normalizes dimensionality: 0-d arrays are promoted with np.atleast_1d, but ndim ≥ 2 raises TypeError because a 2-D key is ambiguous between row and column selection. Only 1-D arrays can select columns.

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 df599052da)

Solutions

  1. Flatten the key: df[key.ravel()] or df[key.reshape(-1)].
  2. Take the relevant axis of a coordinate matrix: df[pairs[:, 0]].
  3. For cell-wise access, iterate row/column pairs or use df.item(row, col).

Example fix

// before
rows, cols = np.where(mask_2d)
sub = df[cols]  # cols is 2-D when mask_2d had >1 row? no: use ravel for safety

// after
sub = df[np.asarray(cols).ravel()]
Defensive patterns

Strategy: validation

Validate before calling

key = np.asarray(key)
if key.ndim == 0:
    key = np.atleast_1d(key)
elif key.ndim != 1:
    key = key.reshape(-1)  # or key.ravel()
out = df[key]

Type guard

def is_1d_index_array(key: np.ndarray) -> bool:
    return key.ndim == 1

Try / catch

try:
    out = df[key]
except TypeError as e:
    if "multi-dimensional NumPy arrays not supported" in str(e):
        out = df[np.asarray(key).reshape(-1)]
    else:
        raise

Prevention

When it happens

Trigger: df[np.array([[0, 1], [2, 3]])]; keys produced by np.where on a 2-D array (returns a tuple of 2-D arrays); index matrices from train/test splitting code.

Common situations: np.where applied to matrices returning multi-dimensional index arrays; one-hot argmax or coordinate-pair outputs (N, 2) passed directly as selectors; forgetting that df[key] selects columns, not arbitrary cells.

Related errors


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