Sorting and uniqueness in Python
sort by several columns, take the top rows, or drop duplicates.
import polars as pl
frame = pl.DataFrame({
"lang": ["python", "rust", "python", "sql"],
"tpm": [104, 98, 91, 79],
})
print(frame.sort(["lang", "tpm"], descending=[False, True]))
print(frame.top_k(2, by="tpm"))
print(frame.unique(subset="lang", keep="first").sort("lang"))
print(frame["lang"].n_unique(), frame.height, frame.width)
How it works
sorttakesdescendingper column.top_kavoids sorting the whole frame.uniquekeeps the first or last row per key.
Keywords and builtins used here
asprint
The run, in numbers
- Lines
- 11
- Characters to type
- 332
- Tokens
- 136
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 78 seconds.
Step 2 of 3 in Filtering & sorting, step 10 of 32 in Polars.