Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.
Sorting and Taking the Top Rows
df.sort_values("score") # ascending
df.sort_values("score", ascending=False) # descending
df.sort_values(["city", "score"]) # by city, then score within city
df.head(3) # the first 3 rowssort_values returns a new frame. It does not sort in place unless you pass inplace=True, and you generally should not: reassigning is clearer and avoids a whole category of "why did my other variable change" confusion.
nlargest does sort-then-head in one step and is faster on a big frame, because it does not have to sort everything:
df.nlargest(3, "score")
One thing to know about the index: after sorting, the row labels come along for the ride, so your top row might be labelled 47. That is correct behaviour, not a bug. .reset_index(drop=True) renumbers if you need tidy labels.
Your task:
Write top_scores(df, n) that returns the n rows with the highest score, highest first.
Example Tests
The two highest scores come back, highest first
Input: {"n":2,"df":{"name":["a","b","c"],"score":[70,95,82]}}
Expected: [95,82]
Asking for one row gives just the single best
Input: {"n":1,"df":{"name":["a","b"],"score":[10,20]}}
Expected: [20]
Asking for more rows than exist returns everything available
Input: {"n":10,"df":{"name":["a"],"score":[5]}}
Expected: [5]
import pandas as pd
def top_scores(df, n):
"""
The n highest-scoring rows.
Args:
df: a DataFrame with a "score" column
n: how many rows to return
Returns:
A DataFrame of n rows, ordered from highest score down.
"""
# YOUR CODE HERE
pass
def _scores(df, n):
import pandas as pd
return [float(v) for v in top_scores(pd.DataFrame(df), n)["score"]]Run your code to see results
⌘↵ runs against the visible tests