Extract Year, Month, Day-of-Week and Quarter Columns From a pandas Timestamp Column
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `date_parts(df)`. The input `df` has a single column `'ts'` of dtype `datetime64[ns]`. Return a new DataFrame that decomposes each timestamp into four calendar components.
Requirements:
- Exactly four columns, in order: `'year'`, `'month'`, `'dayofweek'`, `'quarter'`.
- Derive them with `.dt.year`, `.dt.month`, `.dt.dayofweek` (Monday=0 through Sunday=6) and `.dt.quarter` (1 to 4).
- Every column must have dtype `int32`.
- Keep the same index as `df`, and do not mutate the input.
Example:
```python
df = pd.DataFrame({'ts': pd.to_datetime(['2026-03-15', '2026-11-02'])})
date_parts(df)
# year month dayofweek quarter
# 0 2026 3 6 1
# 1 2026 11 0 4
# all four columns dtype int32
```
March 15, 2026 is a Sunday (6) in the first quarter, and November 2, 2026 is a Monday (0) in the fourth quarter.
```hint Leave the input alone
Adding columns to `df` changes the caller's frame. Assemble a separate DataFrame on the same index, then compare every column's dtype with the contract.
```
### What a Strong Answer Covers
- All four components pulled with the vectorized `.dt` accessor, using the Monday=0 convention for `dayofweek`
- A separate result DataFrame with exactly the four columns in the required order, so `df` is unchanged
- An explicit cast of every column to `int32`, and why the accessor's default dtype is not enough
- The index of `df` carried over to the result
### Follow-up Questions
- How would you also add an `'is_month_end'` boolean column?
- What happens if `'ts'` contains `NaT` values?
- A reporting team wants Sunday=0 through Saturday=6 instead. How would you produce that column?
Overview: Write a pandas function that splits a datetime column into year, month, day-of-week and quarter columns, each typed int32, in a new DataFrame that keeps the input's index. It tests the .dt accessor, dtype control across pandas versions, column ordering and leaving the input frame unmodified.