Build an Inclusive Age Range Boolean Mask in pandas
Quick Overview
Write a pandas function that returns a boolean mask marking rows whose age falls within an inclusive range of 0 to 120, without filtering or changing the DataFrame. It tests inclusive bounds checks, result dtype and naming, and index alignment.
Build an Inclusive Age Range Boolean Mask in pandas
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `in_range_mask(df: pd.DataFrame) -> pd.Series`. The input has columns `['name', 'age']`, where `age` is an integer that may be out of range. Return a boolean mask that is `True` exactly where `age` is in `[0, 120]`.
The mask must meet these requirements:
- Dtype `bool` (not object or int).
- `True` where `0 <= age <= 120` (both bounds inclusive), else `False`.
- Aligned to `df.index`, with the Series name set to `'age'`.
- `df` is not filtered or modified.
Example:
```python
df = pd.DataFrame({'name': ['a', 'b', 'c'], 'age': [-3, 40, 250]})
in_range_mask(df)
# 0 False
# 1 True
# 2 False
# Name: age, dtype: bool
```
```hint Test the boundaries
Check that ages of exactly 0 and exactly 120 come out `True`, and look at what name your result Series carries.
```
### What a Strong Answer Covers
- Inclusive handling of both bounds, including the boundary values 0 and 120.
- The dtype of the result and how the answer guarantees it is bool.
- Index alignment with `df` and the Series name.
- Returning only the mask while leaving `df` unchanged.
### Follow-up Questions
- The `age` column arrives as strings, and some entries are not numbers. How would you build the mask then?
- How would you report how many rows fall below the range and how many fall above it?
- Would you make the bounds parameters? What would you validate about them?
Overview: Write a pandas function that returns a boolean mask marking rows whose age falls within an inclusive range of 0 to 120, without filtering or changing the DataFrame. It tests inclusive bounds checks, result dtype and naming, and index alignment.
Write in_range_mask(df: pd.DataFrame) -> pd.Series. The input has columns ['name', 'age'], where age is an integer that may be out of range. Return a boolean mask that is True exactly where age is in [0, 120].
The mask must meet these requirements:
Dtype
bool
(not object or int).
True
where
0 <= age <= 120
(both bounds inclusive), else
False
.
Aligned to
df.index
, with the Series name set to
'age'
.