polars.Expr.gather#

Expr.gather(
indices: int | Sequence[int] | IntoExpr | Series | np.ndarray[Any, Any],
*,
null_on_oob: bool = False,
) Expr[source]#

Take values by index.

Parameters:
indices

An expression that leads to a UInt32 dtyped Series.

null_on_oob

Behavior if an index is out of bounds:

  • True -> set the result to null

  • False -> raise an error

Returns:
Expr

Expression of the same data type.

See also

Expr.get

Take a single value

Examples

>>> df = pl.DataFrame(
...     {
...         "group": [
...             "one",
...             "one",
...             "one",
...             "two",
...             "two",
...             "two",
...         ],
...         "value": [1, 98, 2, 3, 99, 4],
...     }
... )
>>> df.group_by("group", maintain_order=True).agg(
...     pl.col("value").gather([2, 1])
... )
shape: (2, 2)
┌───────┬───────────┐
│ group ┆ value     │
│ ---   ┆ ---       │
│ str   ┆ list[i64] │
╞═══════╪═══════════╡
│ one   ┆ [2, 98]   │
│ two   ┆ [4, 99]   │
└───────┴───────────┘

Use null_on_oob=True to return null for out-of-bounds indices.

>>> df = pl.DataFrame({"a": [1, 2, 3]})
>>> df.select(pl.col("a").gather([0, 1, 10], null_on_oob=True))
shape: (3, 1)
┌──────┐
│ a    │
│ ---  │
│ i64  │
╞══════╡
│ 1    │
│ 2    │
│ null │
└──────┘