polars/polars-sort-then-head
| Rule | polars-sort-then-head |
|---|---|
| Pack | Polars |
| Severity | info |
| Fix | unsafe, with xpd check --fix --unsafe-fixes |
| Library versions | every version |
For a small number of rows, top_k or bottom_k can avoid a full sort. Sort the small result if its output order matters.
df.sort("x", descending=True).head(5)df.top_k(5, by="x").sort("x", descending=True)What the rule reports
Section titled “What the rule reports”Top-k was 2.51x and 3.96x faster on shuffled keys, and slower on already sorted keys.
How to fix it
Section titled “How to fix it”Use xpd check --fix --unsafe-fixes to rewrite sort(...).head(...) to top_k or bottom_k when output order does not matter.
Message
Section titled “Message”xpd prints this message with the issue. A name that starts with $ stands for code from your file.
For a small number of rows, top_k or bottom_k can avoid a full sort. Sort the small result if its output order matters.Browse the other rules of the Polars pack.