pola-rs/polars · error · TypeError

only 1D NumPy arrays can be treated as indices

Error message

only 1D NumPy arrays can be treated as indices

What it means

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

Source

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

    return s.cast(idx_type)


def _convert_np_ndarray_to_indices(arr: np.ndarray[Any, Any], size: int) -> Series:
    """Convert a NumPy ndarray to indices, taking into account negative values."""
    # Unsigned or signed Numpy array (ordered from fastest to slowest).
    #   - np.uint32 (polars) or np.uint64 (polars_u64_idx) numpy array
    #     indexes.
    #   - Other unsigned numpy array indexes are converted to pl.UInt32
    #     (polars) or pl.UInt64 (polars_u64_idx).
    #   - Signed numpy array indexes are converted pl.UInt32 (polars) or
    #     pl.UInt64 (polars_u64_idx) after negative indexes are converted
    #     to absolute indexes.
    if arr.ndim == 0:
        arr = np.atleast_1d(arr)
    if arr.ndim != 1:
        msg = "only 1D NumPy arrays can be treated as indices"
        raise TypeError(msg)

    idx_type = get_index_type()

    if len(arr) == 0:
        return pl.Series("", [], dtype=idx_type)

    # Numpy array with signed or unsigned integers.
    if arr.dtype.kind not in ("i", "u"):
        if arr.dtype.kind == "b":
            _raise_on_boolean_mask()
        else:
            msg = f"cannot treat NumPy array of type {arr.dtype} as indices"
            raise TypeError(msg)

    if idx_type == UInt32:
        if arr.dtype in {np.int64, np.uint64} and arr.max() >= U32_MAX:
            msg = "index positions should be smaller than 2^32"
            raise ValueError(msg)

View on GitHub (pinned to df599052da)

Solutions

  1. Flatten before indexing: df[arr.ravel()] or df[arr.reshape(-1)]
  2. For (n, 1) arrays squeeze the trailing axis: df[arr.squeeze(-1)]
  3. If you meant element-wise 2D gather, iterate columns explicitly instead of passing the 2D array

Example fix

# before
df[np.array([[0, 2], [4, 6]])]

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

Strategy: type-guard

Validate before calling

import numpy as np

if arr.ndim != 1:
    arr = np.atleast_1d(arr.squeeze()) if arr.ndim == 2 and 1 in arr.shape else arr.ravel()
assert arr.ndim == 1
df[arr]

Type guard

import numpy as np

def is_1d_index_array(arr) -> bool:
    return isinstance(arr, np.ndarray) and arr.ndim == 1

Prevention

When it happens

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

Common situations: np.argmin/np.where over matrices producing 2D results; column vectors from sklearn-style pipelines; forgetting to flatten batched index outputs.

Related errors


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