Filter a pandas DataFrame to rows dated in calendar year 2021
Quick Overview
Write a pandas function that keeps only the rows whose datetime column falls in calendar year 2021, inclusive on both ends, while keeping the original index labels and column order. It tests boolean masks on datetime columns, bound inclusivity and how timestamps with a time of day change the filter.
Filter a pandas DataFrame to rows dated in calendar year 2021
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `filter_range(df)`. The input DataFrame has a `datetime64[ns]` column `date` and a `val` column. Return only the rows whose `date` falls in calendar year 2021.
```python
import pandas as pd
def filter_range(df: pd.DataFrame) -> pd.DataFrame:
...
```
For example:
```python
df = pd.DataFrame({
"date": pd.to_datetime(["2020-12-31", "2021-01-01", "2021-12-31", "2022-01-01"]),
"val": [10, 20, 30, 40],
})
filter_range(df)
# date val
# 1 2021-01-01 20
# 2 2021-12-31 30
```
The first and last rows fall in 2020 and 2022, so only the rows labeled 1 and 2 remain, and they keep those labels.
```hint Building the filter
A single boolean mask over `date` does the selection. Check that rows dated exactly 2021-01-01 and 2021-12-31 both pass it.
```
### Constraints & Assumptions
- `date` is already `datetime64[ns]`, so no parsing is needed.
- The dates carry no time of day (every value is at midnight), as in the example.
- Keep rows with `date` from `2021-01-01` to `2021-12-31`, inclusive on both ends.
- Filter with a boolean mask, for example `df["date"].between("2021-01-01", "2021-12-31")`.
- Preserve the original column order.
- Preserve the original index labels. Do not call `reset_index`.
### What a Strong Answer Covers
- A mask that includes both the first and the last day of 2021.
- How a `datetime64` column compares against string or `Timestamp` bounds.
- Selecting rows so the column order and the original index labels survive.
- What happens to values with a time component, and to missing dates.
### Follow-up Questions
- How would timestamps with a time component (for example `2021-12-31 14:00`) affect the filter?
- How would you generalize this to an arbitrary year passed as an argument?
- How are missing dates (`NaT`) treated by the mask, and what would you do if they had to be reported?
Overview: Write a pandas function that keeps only the rows whose datetime column falls in calendar year 2021, inclusive on both ends, while keeping the original index labels and column order. It tests boolean masks on datetime columns, bound inclusivity and how timestamps with a time of day change the filter.
Implement filter_range(df). The input DataFrame has a datetime64[ns] column date and a val column. Return only the rows whose date falls in calendar year 2021.
import pandas as pd
def filter_range(df: pd.DataFrame) -> pd.DataFrame:
...