82. Split Train and Test With No User in Both
Difficulty: Medium · Topics: Data Prep for AI, Joins, Aggregations
A recommendation model is evaluated on new users. interactions (user_id, item_id, ts, where ts is a 'YYYY-MM-DD' date) holds every interaction so far.
Label every row with split: a user whose first interaction is on or after '2024-03-01' is a test user, and all of their rows are 'test'; every row of every other user is 'train'. A user must never appear on both sides, even if they kept interacting after March. Return user_id, item_id, ts, split.
Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.
Sample data
interactions
| user_id | item_id | ts |
|---|---|---|
| 1 | 10 | 2024-01-15 |
| 1 | 11 | 2024-03-05 |
| 2 | 10 | 2024-03-02 |
| 2 | 12 | 2024-03-09 |
| 3 | 13 | 2024-02-28 |
Expected output
| user_id | item_id | ts | split |
|---|---|---|---|
| 1 | 10 | 2024-01-15 | train |
| 1 | 11 | 2024-03-05 | train |
| 2 | 10 | 2024-03-02 | test |
| 2 | 12 | 2024-03-09 | test |
| 3 | 13 | 2024-02-28 | train |
Hints
Hint 1
Splitting each row by its own date puts an old user's March rows in test: the model has already seen that user, so the score is inflated. That is leakage.Hint 2
Find each user's first date withgroupBy("user_id").agg(F.min("ts")), then join it back to the rows.Hint 3
Dates written as'YYYY-MM-DD' compare correctly as text, so first_ts >= "2024-03-01" works.Learn the concepts
- when / otherwise · 4 min read. CASE WHEN logic inside a column: first match wins, and a missing otherwise means null.
- join · 5 min read. Combine DataFrames on a key: inner, left, right and full joins, and the duplicate-key fan-out trap.
- groupBy + agg · 4 min read. Aggregate rows per group: counts, sums, averages, and how count(*) differs from count(col).
PySpark functions you'll practise
- groupBy
- agg
- min
- join
- when / otherwise
- select
- withColumn
Related problems
- Remove Near-Duplicate Documents · Medium · Data Prep for AI, Window Functions, Strings
- Filter Low-Quality Training Text · Medium · Data Prep for AI, Strings, Null Handling
- Fit Conversations into a Context Window · Hard · Data Prep for AI, Window Functions, Joins
- Build Preference Pairs from Ratings · Hard · Data Prep for AI, Window Functions, Joins
- Mask Personal Data Before Training · Easy · Data Prep for AI, Strings, Filtering & Selection
Browse
Topics: Window Functions · Joins · Aggregations · Pivot, Unpivot & Rollup · Arrays · Null Handling · Conditional Logic · Dates · Filtering & Selection · Strings · Data Lake · Lakehouse · Streaming · Data Prep for AI · Spark Performance
Difficulty: Easy · Medium · Hard · Learn · All problems · dbt practice