typestar

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

  1. sort takes descending per column.
  2. top_k avoids sorting the whole frame.
  3. unique keeps the first or last row per key.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Filtering & sorting, step 10 of 32 in Polars.

← Previous Next →