BasicsPandasDatetimeMetaAmazonUber
Problem
Implement add_year_month(df) returning a copy of df that parses ISO date strings in order_date using pd.to_datetime and appends integer columns year and month.
Why It Matters: Extracting calendar features (year, month, dayofweek) is fundamental for time-series forecasting, cohort grouping, and seasonality modeling.
Function Signature
import pandas as pd
def add_year_month(df: pd.DataFrame) -> pd.DataFrame:
Sample Input & Output
Example 1: Multiple Dates
Input:
| order_id | order_date |
|---|---|
| 1 | 2025-01-15 |
| 2 | 2026-11-30 |
Expected Output:
| order_id | order_date | year | month |
|---|---|---|---|
| 1 | 2025-01-15 | 2025 | 1 |
| 2 | 2026-11-30 | 2026 | 11 |
Explanation: Extracts (2025, 1) and (2026, 11) as integer columns.
Example 2: Leap Day Date
Input:
| order_id | order_date |
|---|---|
| 3 | 2024-02-29 |
Expected Output:
| order_id | order_date | year | month |
|---|---|---|---|
| 3 | 2024-02-29 | 2024 | 2 |
Explanation: Parses leap-year February 29 cleanly into year = 2024, month = 2.
Constraints & Edge Cases
- Add integer columns
'year'and'month'. - Use
pd.to_datetime(out['order_date'])and.dt.year/.dt.month. - Do not mutate
dfin place.
Constraints & Evaluation Criteria
- Add integer columns `'year'` and `'month'`.
Hints
Python 3⌘/Ctrl+Enter to Run · ⌘/Ctrl+Shift+Enter to Submit
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
['2025-03-15', '2026-11-02']
Expected Output / Criteria
year=[2025,2026], month=[3,11]