Cyclical Datetime Encoder Transformer

Quick Overview

Build a scikit-learn transformer that replaces a datetime column with sine and cosine encodings of hour, day of week and month. It tests cyclical feature encoding, pandas datetime handling with strings and missing values, and the estimator conventions that let a custom transformer work inside a Pipeline.

Cyclical Datetime Encoder Transformer

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: easy

Interview Round: Other

Implement `CyclicalDatetimeEncoder`, a scikit-learn transformer that takes a DataFrame with a datetime column `column` (default `"timestamp"`). It replaces that column with sine/cosine encodings of hour, day of week and month, and returns a DataFrame. Requirements: - Angle = ${2\pi \cdot v / \text{period}}$: hour (0 to 23, period 24), `dayofweek` (Monday = 0, period 7), month minus 1 (0 to 11, period 12). - Drop the raw column, keep the other columns in order and the index, then append `{column}_{hour|dow|month}_{sin|cos}` (sin before cos, in the order hour, dow, month) as `float64`. - Parse string timestamps. Missing timestamps give `NaN` in all six new columns. Never mutate the input. - `fit` and `transform` raise `KeyError` if the column is absent. `fit` records `feature_names_in_`. - `get_feature_names_out()` returns exactly the transformed column names. The transformer works inside a `Pipeline`. For example: ```python df = pd.DataFrame({"ts": pd.to_datetime(["2024-01-01 06:00"]), "v": [5]}) CyclicalDatetimeEncoder(column="ts").fit_transform(df) # columns: v, ts_hour_sin, ts_hour_cos, ts_dow_sin, ts_dow_cos, ts_month_sin, ts_month_cos # values: 5, 1.0, ~0.0, 0.0, 1.0, 0.0, 1.0 ``` ```hint Missing values and dtypes Check what the `.dt.hour`, `.dt.dayofweek` and `.dt.month` accessors return on a column that contains a missing timestamp, and which dtype the parts need before you apply `sin` and `cos`. ``` ### What a Strong Answer Covers - The angle for each part with the right period and offset (month minus 1, Monday as 0), and why both sine and cosine are needed. - Column handling: the raw column dropped, other columns and the index kept in order, six `float64` columns appended in the required order, and the input left unchanged. - String parsing, missing timestamps, and the `KeyError` checks in both `fit` and `transform`. - The scikit-learn conventions that make it work in a `Pipeline`, including a `get_feature_names_out` that matches what `transform` returns. ### Follow-up Questions - Why encode cyclically instead of using raw hour integers? - How would you handle timezone-aware timestamps? - Would a gradient-boosted tree model benefit from this encoding as much as a linear model?

Overview: Build a scikit-learn transformer that replaces a datetime column with sine and cosine encodings of hour, day of week and month. It tests cyclical feature encoding, pandas datetime handling with strings and missing values, and the estimator conventions that let a custom transformer work inside a Pipeline.

General logo
General
Nov 24, 2026
easyMachine Learning EngineerOtherMachine Learning
0
0

Implement CyclicalDatetimeEncoder, a scikit-learn transformer that takes a DataFrame with a datetime column column (default "timestamp"). It replaces that column with sine/cosine encodings of hour, day of week and month, and returns a DataFrame.

Requirements:

  • Angle = 2π⋅v/period{2\pi \cdot v / \text{period}} : hour (0 to 23, period 24), dayofweek (Monday = 0, period 7), month minus 1 (0 to 11, period 12).
  • Drop the raw column, keep the other columns in order and the index, then append {column}_{hour|dow|month}_{sin|cos} (sin before cos, in the order hour, dow, month) as float64 .
  • Parse string timestamps. Missing timestamps give NaN in all six new columns. Never mutate the input.
  • fit and transform raise KeyError if the column is absent. fit records feature_names_in_ .
  • get_feature_names_out() returns exactly the transformed column names. The transformer works inside a Pipeline .

For example:

df = pd.DataFrame({"ts": pd.to_datetime(["2024-01-01 06:00"]), "v": [5]})
CyclicalDatetimeEncoder(column="ts").fit_transform(df)
# columns: v, ts_hour_sin, ts_hour_cos, ts_dow_sin, ts_dow_cos, ts_month_sin, ts_month_cos
# values:  5, 1.0,         ~0.0,        0.0,        1.0,        0.0,          1.0

What a Strong Answer Covers Guidance

  • The angle for each part with the right period and offset (month minus 1, Monday as 0), and why both sine and cosine are needed.
  • Column handling: the raw column dropped, other columns and the index kept in order, six float64 columns appended in the required order, and the input left unchanged.
  • String parsing, missing timestamps, and the KeyError checks in both fit and transform .
  • The scikit-learn conventions that make it work in a Pipeline , including a get_feature_names_out that matches what transform returns.

Follow-up Questions Guidance

  • Why encode cyclically instead of using raw hour integers?
  • How would you handle timezone-aware timestamps?
  • Would a gradient-boosted tree model benefit from this encoding as much as a linear model?