polars.nth#
- polars.nth(n: int | Sequence[int], *columns: str) Expr [source]#
Get the nth column(s) or value(s).
This function has different behavior depending on the presence of
columns
values. If none given (the default), returns an expression that takes the nth column of the context; otherwise, takes the nth value of the given column(s).- Parameters:
- n
One or more indices representing the columns/values to retrieve.
- *columns
One or more column names. If omitted (the default), returns an expression that takes the nth column of the context; otherwise, takes the nth value of the given column(s).
Examples
>>> df = pl.DataFrame( ... { ... "a": [1, 8, 3], ... "b": [4, 5, 2], ... "c": ["foo", "bar", "baz"], ... } ... )
Return the “nth” column(s):
>>> df.select(pl.nth(1)) shape: (3, 1) ┌─────┐ │ b │ │ --- │ │ i64 │ ╞═════╡ │ 4 │ │ 5 │ │ 2 │ └─────┘
>>> df.select(pl.nth([2, 0])) shape: (3, 2) ┌─────┬─────┐ │ c ┆ a │ │ --- ┆ --- │ │ str ┆ i64 │ ╞═════╪═════╡ │ foo ┆ 1 │ │ bar ┆ 8 │ │ baz ┆ 3 │ └─────┴─────┘
Return the “nth” value(s) for the given columns:
>>> df.select(pl.nth(-2, "b", "c")) shape: (1, 2) ┌─────┬─────┐ │ b ┆ c │ │ --- ┆ --- │ │ i64 ┆ str │ ╞═════╪═════╡ │ 5 ┆ bar │ └─────┴─────┘
>>> df.select(pl.nth([0, 2], "c", "a")) shape: (2, 2) ┌─────┬─────┐ │ c ┆ a │ │ --- ┆ --- │ │ str ┆ i64 │ ╞═════╪═════╡ │ foo ┆ 1 │ │ baz ┆ 3 │ └─────┴─────┘