pandas: Sort by several columns

Model sort_values with a list of columns and a direction for each, plus pandas' rule for missing values.

What to build

A program that sorts a table by several columns.

Requirements

  • The sort spec is a list like city asc, score desc. Numeric columns compare as numbers, others as text. Rows with an empty value in a key column go after all rows with a value for that key, in either direction. Equal rows keep their input order.
  • Print the name of each row in sorted order, one per line.

Input

Line 1: the header (it includes name). Line 2: n. Then n rows, values separated by commas. Last line: the sort spec.

Output

n lines.

Constraints

1 ≤ n ≤ 100; 1 to 3 keys.

Example

Input:

name,city,score
5
Ada,London,88
Rahim,Dhaka,92
Mei,Dhaka,88
Omar,London,
Lena,Dhaka,75
city asc, score desc

Output:

Rahim
Mei
Lena
Ada
Omar

Why it works

A stable sort applied from the least to the most important key leaves rows ordered by the first key, then the second within ties, and so on, which is how a multi-column sort_values behaves.

Examples

Example 1 · Input
name,city,score
5
Ada,London,88
Rahim,Dhaka,92
Mei,Dhaka,88
Omar,London,
Lena,Dhaka,75
city asc, score desc
Expected output
Rahim
Mei
Lena
Ada
Omar
Example 2 · Input
name,score
3
a,10
b,9
c,10
score desc
Expected output
a
c
b

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Sort in several passes from the last key to the first; Python's sort is stable, so earlier passes survive as tie-breakers.

Hint 2

Put rows with an empty value in the key column at the end, whatever the direction.

Solution

Show one correct solution (try it yourself first)
def number(text):
    try:
        return float(text)
    except ValueError:
        return None


header = input().split(",")
n = int(input())
rows = [dict(zip(header, input().split(","))) for _ in range(n)]
spec = [part.split() for part in input().split(", ")]
for column, direction in reversed(spec):
    present = [r for r in rows if r[column] != ""]
    missing = [r for r in rows if r[column] == ""]
    numeric = all(number(r[column]) is not None for r in present)
    key = (lambda r: number(r[column])) if numeric else (lambda r: r[column])
    rows = sorted(present, key=key, reverse=direction == "desc") + missing
for r in rows:
    print(r["name"])

Lesson: Sorting, ranking and counting →