polars.Expr.sort#

Expr.sort(reverse: bool = False, nulls_last: bool = False) Expr[source]#

Sort this column. In projection/ selection context the whole column is sorted.

If used in a groupby context, the groups are sorted.

Parameters:
reverse

False -> order from small to large. True -> order from large to small.

nulls_last

If True nulls are considered to be larger than any valid value

Examples

>>> df = pl.DataFrame(
...     {
...         "group": [
...             "one",
...             "one",
...             "one",
...             "two",
...             "two",
...             "two",
...         ],
...         "value": [1, 98, 2, 3, 99, 4],
...     }
... )
>>> df.select(pl.col("value").sort())
shape: (6, 1)
┌───────┐
│ value │
│ ---   │
│ i64   │
╞═══════╡
│ 1     │
├╌╌╌╌╌╌╌┤
│ 2     │
├╌╌╌╌╌╌╌┤
│ 3     │
├╌╌╌╌╌╌╌┤
│ 4     │
├╌╌╌╌╌╌╌┤
│ 98    │
├╌╌╌╌╌╌╌┤
│ 99    │
└───────┘
>>> df.select(pl.col("value").sort())
shape: (6, 1)
┌───────┐
│ value │
│ ---   │
│ i64   │
╞═══════╡
│ 1     │
├╌╌╌╌╌╌╌┤
│ 2     │
├╌╌╌╌╌╌╌┤
│ 3     │
├╌╌╌╌╌╌╌┤
│ 4     │
├╌╌╌╌╌╌╌┤
│ 98    │
├╌╌╌╌╌╌╌┤
│ 99    │
└───────┘
>>> df.groupby("group").agg(pl.col("value").sort())  
shape: (2, 2)
┌───────┬────────────┐
│ group ┆ value      │
│ ---   ┆ ---        │
│ str   ┆ list[i64]  │
╞═══════╪════════════╡
│ two   ┆ [3, 4, 99] │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤
│ one   ┆ [1, 2, 98] │
└───────┴────────────┘