Skip to content

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_iditem_idts
1102024-01-15
1112024-03-05
2102024-03-02
2122024-03-09
3132024-02-28

Expected output

user_iditem_idtssplit
1102024-01-15train
1112024-03-05train
2102024-03-02test
2122024-03-09test
3132024-02-28train

Hints

Hint 1Splitting 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 2Find each user's first date with groupBy("user_id").agg(F.min("ts")), then join it back to the rows.
Hint 3Dates written as 'YYYY-MM-DD' compare correctly as text, so first_ts >= "2024-03-01" works.

Learn the concepts

PySpark functions you'll practise

Related problems

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