Filter a Pandas DataFrame with a Multi-Condition Boolean Mask
Quick Overview
Write a pandas function that keeps the rows whose age falls in an inclusive range and whose active flag is true, using one combined boolean mask. It tests element-wise operators, operator precedence in pandas filters, and preserving the index without mutating the input.
Filter a Pandas DataFrame with a Multi-Condition Boolean Mask
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `filter_active_in_range(df, lo, hi)` that selects the rows where the integer `'age'` column is within the inclusive range `[lo, hi]` and the boolean `'active'` column is `True`.
The function must meet these requirements:
- Return only the rows satisfying `lo <= age <= hi` and `active == True`.
- Build one combined mask: wrap each condition in parentheses and join the conditions with `&`.
- Do not use the Python `and` keyword (it raises on a Series).
- Keep all columns and preserve the original index and row order.
- Do not mutate the input `df`.
Example:
```python
df = pd.DataFrame({
'age': [17, 25, 40, 30],
'active': [True, True, False, True],
})
filter_active_in_range(df, 18, 35)
# age active
# 1 25 True
# 3 30 True
```
```hint Masks line up by index
Each condition gives a boolean Series aligned to the frame's index. Work out what each one looks like on the example, then think about how indexing a DataFrame with a single boolean Series behaves.
```
### Constraints & Assumptions
- The `'age'` and `'active'` columns exist with the stated dtypes.
### What a Strong Answer Covers
- Combining the lower bound, upper bound and activity conditions into one element-wise mask.
- Why `&` works where `and` fails, and why each comparison needs parentheses.
- Keeping every column, the original index labels and the row order in the result.
- Leaving the input frame unchanged.
- The cost of building the mask over the whole frame.
### Follow-up Questions
- Why does `and` fail where `&` works on a Series?
- How would you extend this to accept an optional list of allowed categories?
- How should the filter treat rows whose `active` or `age` value is missing?
Overview: Write a pandas function that keeps the rows whose age falls in an inclusive range and whose active flag is true, using one combined boolean mask. It tests element-wise operators, operator precedence in pandas filters, and preserving the index without mutating the input.
Implement filter_active_in_range(df, lo, hi) that selects the rows where the integer 'age' column is within the inclusive range [lo, hi] and the boolean 'active' column is True.
The function must meet these requirements:
Return only the rows satisfying
lo <= age <= hi
and
active == True
.
Build one combined mask: wrap each condition in parentheses and join the conditions with
&
.
Do not use the Python
and
keyword (it raises on a Series).
Keep all columns and preserve the original index and row order.