Filter pandas DataFrame rows above a score threshold with a boolean mask
Quick Overview
Implement a pandas function that keeps only the DataFrame rows whose score is strictly above a threshold, using one boolean mask. It tests vectorized comparisons, boolean indexing, preserving the original index, and handling missing or non-numeric values.
Filter pandas DataFrame rows above a score threshold with a boolean mask
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `filter_above(df: pd.DataFrame, threshold: float) -> pd.DataFrame` that returns all rows where the `'score'` column is strictly greater than `threshold`.
The function must meet these requirements:
- Keep only rows where `df['score'] > threshold` (strict, not `>=`).
- Return all columns unchanged.
- Preserve the original index labels and row order. Do not call `reset_index()`.
- Use a single boolean mask. Do not iterate over rows.
For example:
```python
df = pd.DataFrame({'score': [70, 85, 60, 90]})
filter_above(df, 75)
# score
# 1 85
# 3 90
```
```hint Check the boundary and the labels
Run the example again with a threshold of 85 and decide which rows should survive. Then check that each surviving row keeps the index label it had in the input.
```
### What a Strong Answer Covers
- How a vectorized comparison on the `score` column produces one boolean Series aligned to the frame's index
- Why the comparison is strict, and what happens to a row whose score equals the threshold
- How indexing with the mask keeps every column, the original labels and the original order
- What the function returns for missing scores, an empty frame and a threshold that no row passes
- The time and memory cost compared with looping over rows
### Follow-up Questions
- How would you make the column name a parameter with `'score'` as the default?
- Rows with a missing score are dropped by this filter. How would you keep them if the caller asked for that?
- How would you add a second condition on another column to the same mask?
- If the caller assigns a new column on the returned frame, what warning can pandas raise, and how do you avoid it?
Overview: Implement a pandas function that keeps only the DataFrame rows whose score is strictly above a threshold, using one boolean mask. It tests vectorized comparisons, boolean indexing, preserving the original index, and handling missing or non-numeric values.
Implement filter_above(df: pd.DataFrame, threshold: float) -> pd.DataFrame that returns all rows where the 'score' column is strictly greater than threshold.
The function must meet these requirements:
Keep only rows where
df['score'] > threshold
(strict, not
>=
).
Return all columns unchanged.
Preserve the original index labels and row order. Do not call
reset_index()
.
Use a single boolean mask. Do not iterate over rows.