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.
Selecting Columns and Filtering Rows
One column comes back as a Series, which is a single labelled column:
df["score"] # a Series df[["name", "score"]] # a DataFrame, note the double brackets
Double brackets mean "a list of column names", which is why selecting several columns looks like that.
Filtering rows uses a boolean condition, exactly like NumPy's boolean indexing:
df["score"] > 80 # a Series of True/False, one per row df[df["score"] > 80] # only the rows where that was True
Combining conditions needs & and |, not and and or, and every condition needs its own parentheses:
df[(df["score"] > 80) & (df["score"] < 95)] # correct df[df["score"] > 80 and df["score"] < 95] # ValueError
The parentheses are not optional. & binds more tightly than >, so without them Python tries to evaluate 80 & df["score"] first and the error message will not point at the real problem.
Your task:
Write high_scorers(df, threshold) that returns the rows where score is strictly greater than threshold.
Example Tests
Only rows above the threshold survive
Input: {"df":{"name":["a","b","c"],"score":[90,70,85]},"threshold":80}
Expected: [2,2]
A row exactly at the threshold is excluded, since the test is strict
Input: {"df":{"name":["a","b"],"score":[80,81]},"threshold":80}
Expected: [1,2]
Nothing above the threshold gives an empty frame, not an error
Input: {"df":{"name":["a"],"score":[10]},"threshold":50}
Expected: [0,2]
import pandas as pd
def high_scorers(df, threshold):
"""
Keep only the rows above a score threshold.
Args:
df: a DataFrame with a "score" column
threshold: a number
Returns:
The subset of rows where score > threshold.
"""
# YOUR CODE HERE
pass
def _run(df, threshold):
"""Builds a DataFrame from plain data, then calls high_scorers."""
import pandas as pd
return high_scorers(pd.DataFrame(df), threshold)
def _score_total(df, threshold):
"""Total of the surviving score column."""
import pandas as pd
return float(high_scorers(pd.DataFrame(df), threshold)["score"].sum())Run your code to see results
⌘↵ runs against the visible tests