typestar

Sorting and ranking in Python

Sort by values or by index, and rank without reordering.

import pandas as pd

frame = pd.DataFrame({
    "lang": ["python", "rust", "sql", "css"],
    "tpm": [104, 98, 104, 79],
    "stars": [3, 3, 2, 1],
})

print(frame.sort_values(["tpm", "stars"], ascending=[False, True]))
print(frame.nlargest(2, "tpm"))
print(frame["tpm"].rank(method="min", ascending=False).tolist())

How it works

  1. sort_values takes one column or a list, with ascending per column.
  2. nlargest is the cheap way to ask for a top ten.
  3. rank numbers the rows in place, ties averaged by default.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
304
Tokens
127
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 73 seconds.

Type this snippet

Step 4 of 4 in Selecting rows, step 8 of 26 in pandas.

← Previous Next →