Implementation:Pola rs Polars DataFrame Sort by Time
| Knowledge Sources | |
|---|---|
| Domains | Data Engineering, Time Series |
| Last Updated | 2026-02-09 10:00 GMT |
Overview
Concrete API for sorting a Polars DataFrame by a temporal column to establish chronological order required by downstream time series operations.
Description
DataFrame.sort(by) sorts the entire DataFrame by the specified column(s). When by refers to a temporal column (Date, Datetime), the sort produces a chronologically ordered DataFrame. This is typically performed immediately after data ingestion and date parsing, before any time-dependent operations are applied.
The sort is not in-place -- it returns a new DataFrame. This aligns with Polars' immutable DataFrame design, where operations produce new frames rather than mutating existing ones.
Usage
Use DataFrame.sort whenever you need to:
- Establish chronological order after reading and parsing temporal data.
- Prepare data as input to
group_by_dynamic,rolling, orupsample. - Reset ordering after joins or filters that may disrupt temporal order.
Code Reference
Source Location
- Repository: Polars
- File:
docs/source/src/python/user-guide/transformations/time-series/rolling.py(line 10)
Signature
DataFrame.sort(
by: str | Expr | Sequence[str | Expr],
*more_by: str | Expr,
descending: bool | Sequence[bool] = False,
nulls_last: bool | Sequence[bool] = False,
multithreaded: bool = True,
maintain_order: bool = False,
) -> DataFrame
Import
import polars as pl
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| by | Expr | Sequence[str | Expr] | Yes | Column name or expression to sort by (typically a datetime column name) |
| descending | Sequence[bool] | No | If True, sort in descending (newest-first) order (default: False, i.e., ascending/oldest-first) |
| nulls_last | Sequence[bool] | No | If True, place null values at the end (default: False) |
| maintain_order | bool |
No | If True, preserve the relative order of equal elements -- stable sort (default: False) |
Outputs
| Name | Type | Description |
|---|---|---|
| result | pl.DataFrame |
A new DataFrame sorted by the specified column(s) in the requested order |
Usage Examples
Basic Temporal Sort
import polars as pl
df = pl.read_csv("apple_stock.csv", try_parse_dates=True)
df = df.sort("Date")
print(df.head())
Sort Before Dynamic Grouping
import polars as pl
df = pl.read_csv("apple_stock.csv", try_parse_dates=True)
df = df.sort("Date")
# Now safe to use group_by_dynamic
annual = df.group_by_dynamic("Date", every="1y").agg(
pl.col("Close").mean()
)
Descending Sort
import polars as pl
# Sort newest-first for display purposes
df_recent_first = df.sort("Date", descending=True)