Data & Features ยท Medium
Time-Based Train/Test Split
Split events chronologically without future leakage.
Task
Implement train_test_split_by_time(timestamps: list[float], test_size: int) -> tuple[list[int], list[int]]. Return original row indices for a chronological train/test split, using the earliest rows for training and the latest rows for testing.
Requirements
- test_size is an integer between 0 and len(timestamps), inclusive.
- Sort rows by timestamp in ascending order before splitting.
- The sort must be stable: rows with equal timestamps retain their original relative order.
- Return original row indices, not sorted positions or timestamp values.
- The training output contains the first len(timestamps) - test_size sorted indices, and the test output contains the remaining sorted indices.
- Every training timestamp must be less than or equal to every test timestamp, preventing future observations from entering the training split.
- Do not shuffle, mutate timestamps, or use test rows to decide the ordering of equal-time training rows.
- When test_size is 0, return every sorted index in training and an empty test list.
- When test_size equals len(timestamps), return an empty training list and every sorted index in testing.
Example
train_test_split_by_time([30.0, 10.0, 20.0, 20.0, 40.0], 2)
# ([1, 2, 3], [0, 4])