polars.LazyFrame.sort#

LazyFrame.sort(by: Union[str, Expr, Sequence[str], Sequence[Expr], Sequence[str | Expr]], reverse: Union[bool, Sequence[bool]] = False, nulls_last: bool = False) LDF[source]#

Sort the DataFrame.

Sorting can be done by:

  • A single column name

  • An expression

  • Multiple expressions

Parameters:
by

Column (expressions) to sort by.

reverse

Sort in descending order.

nulls_last

Place null values last. Can only be used if sorted by a single column.

Examples

>>> df = pl.DataFrame(
...     {
...         "foo": [1, 2, 3, None],
...         "bar": [6.0, 7.0, 8.0, 9.0],
...         "ham": ["a", "b", "c", "d"],
...     }
... ).lazy()
>>> df.sort("foo").collect()
shape: (4, 3)
┌──────┬─────┬─────┐
│ foo  ┆ bar ┆ ham │
│ ---  ┆ --- ┆ --- │
│ i64  ┆ f64 ┆ str │
╞══════╪═════╪═════╡
│ null ┆ 9.0 ┆ d   │
├╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┤
│ 1    ┆ 6.0 ┆ a   │
├╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┤
│ 2    ┆ 7.0 ┆ b   │
├╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┤
│ 3    ┆ 8.0 ┆ c   │
└──────┴─────┴─────┘
>>> df.sort("foo", nulls_last=True).collect()
shape: (4, 3)
┌──────┬─────┬─────┐
│ foo  ┆ bar ┆ ham │
│ ---  ┆ --- ┆ --- │
│ i64  ┆ f64 ┆ str │
╞══════╪═════╪═════╡
│ 1    ┆ 6.0 ┆ a   │
├╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┤
│ 2    ┆ 7.0 ┆ b   │
├╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┤
│ 3    ┆ 8.0 ┆ c   │
├╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┤
│ null ┆ 9.0 ┆ d   │
└──────┴─────┴─────┘
>>> df.sort("foo", reverse=True).collect()
shape: (4, 3)
┌──────┬─────┬─────┐
│ foo  ┆ bar ┆ ham │
│ ---  ┆ --- ┆ --- │
│ i64  ┆ f64 ┆ str │
╞══════╪═════╪═════╡
│ 3    ┆ 8.0 ┆ c   │
├╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┤
│ 2    ┆ 7.0 ┆ b   │
├╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┤
│ 1    ┆ 6.0 ┆ a   │
├╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┤
│ null ┆ 9.0 ┆ d   │
└──────┴─────┴─────┘

Sort by multiple columns. For multiple columns we can also use expression syntax.

>>> df.sort(
...     [pl.col("foo"), pl.col("bar") ** 2],
...     reverse=[True, False],
... ).collect()
shape: (4, 3)
┌──────┬─────┬─────┐
│ foo  ┆ bar ┆ ham │
│ ---  ┆ --- ┆ --- │
│ i64  ┆ f64 ┆ str │
╞══════╪═════╪═════╡
│ 3    ┆ 8.0 ┆ c   │
├╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┤
│ 2    ┆ 7.0 ┆ b   │
├╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┤
│ 1    ┆ 6.0 ┆ a   │
├╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┤
│ null ┆ 9.0 ┆ d   │
└──────┴─────┴─────┘