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
sort_valuestakes one column or a list, withascendingper column.nlargestis the cheap way to ask for a top ten.ranknumbers the rows in place, ties averaged by default.
Keywords and builtins used here
asprint
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.
Step 4 of 4 in Selecting rows, step 8 of 26 in pandas.