{"record":{"id":"cec426344fd062b4","repo":"pola-rs/polars","slug":"invalid-index-value-idx-r","errorCode":null,"errorMessage":"invalid index value: {idx!r}","messagePattern":"invalid index value: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/selectors.py","lineNumber":1202,"sourceCode":"    >>> df.select(~cs.by_index(range(1, 100, 2)))\n    shape: (1, 51)\n    ┌─────┬─────┬─────┬─────┬───┬──────┬──────┬──────┬──────┐\n    │ key ┆ c01 ┆ c03 ┆ c05 ┆ … ┆ c93  ┆ c95  ┆ c97  ┆ c99  │\n    │ --- ┆ --- ┆ --- ┆ --- ┆   ┆ ---  ┆ ---  ┆ ---  ┆ ---  │\n    │ str ┆ f64 ┆ f64 ┆ f64 ┆   ┆ f64  ┆ f64  ┆ f64  ┆ f64  │\n    ╞═════╪═════╪═════╪═════╪═══╪══════╪══════╪══════╪══════╡\n    │ abc ┆ 0.5 ┆ 1.5 ┆ 2.5 ┆ … ┆ 46.5 ┆ 47.5 ┆ 48.5 ┆ 49.5 │\n    └─────┴─────┴─────┴─────┴───┴──────┴──────┴──────┴──────┘\n    \"\"\"\n    all_indices: builtins.list[int] = []\n    for idx in indices:\n        if isinstance(idx, (range, Sequence)):\n            all_indices.extend(idx)  # type: ignore[arg-type]\n        elif isinstance(idx, int):\n            all_indices.append(idx)\n        else:\n            msg = f\"invalid index value: {idx!r}\"\n            raise TypeError(msg)\n\n    return Selector._from_pyselector(PySelector.by_index(all_indices, require_all))\n\n\ndef by_name(*names: str | Collection[str], require_all: bool = True) -> Selector:\n    \"\"\"\n    Select all columns matching the given names.\n\n    .. versionadded:: 0.20.27\n      The `require_all` parameter was added.\n\n    Parameters\n    ----------\n    *names\n        One or more names of columns to select.\n    require_all\n        Whether to match *all* names (the default) or *any* of the names.\n","sourceCodeStart":1184,"sourceCodeEnd":1220,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/selectors.py#L1184-L1220","documentation":"Thrown by cs.by_index (py-polars/src/polars/selectors.py:1202) when an argument is neither an int, a range, nor a Sequence. by_index flattens ints, ranges, and sequences of ints into one index list; any other object (a string like \"0\", a float like 1.5, a numpy scalar that is not a Python int) fails with TypeError.","triggerScenarios":"cs.by_index(\"0\"), cs.by_index(1.5), cs.by_index(np.int64(0)) is fine (int subclass), but cs.by_index(\"0,1,2\") or cs.by_index([0, 1.5]) fail — 1.5 inside a list is not an int and is appended unchecked via extend, but a float top-level arg raises here.","commonSituations":"Indices parsed from CLI args or JSON are strings; numpy float indices from np.where(...)[0] style code that yields floats; hardcoding a float by mistake.","solutions":["Pass ints, ranges, or sequences of ints: cs.by_index(0), cs.by_index(range(3)), cs.by_index([0, 1, 2])","Convert parsed values: cs.by_index(int(arg)) or cs.by_index([int(i) for i in arg.split(\",\")])","For numpy float results use cs.by_index(np.where(cond)[0].astype(int))"],"exampleFix":"# before\ncols = df.select(cs.by_index(\"0\"))  # str index from CLI/JSON\n\n# after\ncols = df.select(cs.by_index(int(\"0\")))\n# or\ncols = df.select(cs.by_index([int(i) for i in [\"0\", \"1\"]]))","handlingStrategy":"validation","validationCode":"from polars import selectors as cs\n\nidx = [int(i) for i in \"0,2,5\".split(\",\")]  # strings from CLI/JSON\nsel = cs.by_index(idx)","typeGuard":"from collections.abc import Sequence\nfrom typing import TypeGuard\n\ndef is_index_arg(x: object) -> TypeGuard[int | range | Sequence[int | range]]:\n    return isinstance(x, (int, range, Sequence))","tryCatchPattern":"try:\n    sel = cs.by_index(*raw)\nexcept TypeError as e:\n    if \"invalid index value\" in str(e):\n        raw = [int(x) if isinstance(x, str) else x for x in raw]\n        sel = cs.by_index(*raw)\n    else:\n        raise","preventionTips":["Coerce CLI/JSON indices to int at the boundary","Cast numpy results explicitly: arr.astype(int) before passing to by_index"],"tags":["polars","selectors","typeerror","index","column-selection"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}