pola-rs/polars · error · TypeError

invalid index value

Error message

invalid index value: {idx!r}

What it means

polars.selectors.by_index() raises this TypeError when an element passed as part of `idx` is not an int or a range/Sequence. Only integers (or collections/ranges of integers) are valid column indices for a selector; anything else (e.g. a string, float, or nested list) is rejected before building the PySelector.

Solutions

  1. Convert all values to int: cs.by_index(*(int(i) for i in idx))
  2. Check whether you meant cs.by_name() if you are passing column name strings
  3. Filter/validate: idx = [i for i in idx if isinstance(i, int)] before calling
  4. Cast NumPy scalar indices with .item() if needed

Example fix

// before
cs.by_index(0, "col_a", 2.0)
// after
cs.by_index(0, 2)  # strings -> use cs.by_name("col_a"); use int() on numerics
Defensive patterns

Strategy: type-guard

Validate before calling

def valid_indices(idx):
    if isinstance(idx, int) or isinstance(idx, (range, Sequence)):
        items = [idx] if isinstance(idx, int) else list(idx)
        return all(isinstance(i, int) for i in items)
    return False
assert valid_indices(my_idx)

Type guard

def is_index_value(x) -> bool:
    return isinstance(x, int) or (isinstance(x, (range, Sequence)) and all(isinstance(i, int) for i in x))

Try / catch

try:
    sel = cs.by_index(idx)
except TypeError:
    sel = cs.by_index(*(int(i) for i in idx if isinstance(i, (int, float))))

Prevention

When it happens

Trigger: Calling cs.by_index(0, "a"), cs.by_index(1.5), cs.by_index([0, "b"]), or passing a nested structure like cs.by_index([[0,1]]) — any non-int element or non-Sequence/non-int top-level argument.

Common situations: Mixing up by_index with by_name and passing column names (strings); building indices programmatically where a None or float slipped in (e.g. from np.argpartition results or division); NumPy integer types are fine but Python floats from parsing config values are not.

Understand the failure class

Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.

Related errors


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

Appendix: source

Thrown at py-polars/src/polars/selectors.py:1194

    >>> df.select(~cs.by_index(range(1, 100, 2)))
    shape: (1, 51)
    ┌─────┬─────┬─────┬─────┬───┬──────┬──────┬──────┬──────┐
    │ key ┆ c01 ┆ c03 ┆ c05 ┆ … ┆ c93  ┆ c95  ┆ c97  ┆ c99  │
    │ --- ┆ --- ┆ --- ┆ --- ┆   ┆ ---  ┆ ---  ┆ ---  ┆ ---  │
    │ str ┆ f64 ┆ f64 ┆ f64 ┆   ┆ f64  ┆ f64  ┆ f64  ┆ f64  │
    ╞═════╪═════╪═════╪═════╪═══╪══════╪══════╪══════╪══════╡
    │ abc ┆ 0.5 ┆ 1.5 ┆ 2.5 ┆ … ┆ 46.5 ┆ 47.5 ┆ 48.5 ┆ 49.5 │
    └─────┴─────┴─────┴─────┴───┴──────┴──────┴──────┴──────┘
    """
    all_indices: builtins.list[int] = []
    for idx in indices:
        if isinstance(idx, (range, Sequence)):
            all_indices.extend(idx)  # type: ignore[arg-type]
        elif isinstance(idx, int):
            all_indices.append(idx)
        else:
            msg = f"invalid index value: {idx!r}"
            raise TypeError(msg)

    return Selector._from_pyselector(PySelector.by_index(all_indices, require_all))


def by_name(*names: str | Collection[str], require_all: bool = True) -> Selector:
    """
    Select all columns matching the given names.

    .. versionadded:: 0.20.27
      The `require_all` parameter was added.

    Parameters
    ----------
    *names
        One or more names of columns to select.
    require_all
        Whether to match *all* names (the default) or *any* of the names.

View on GitHub (pinned to fe841f959e)