Keep only the latest subscription record per user

Easypandas

Billing tables for AI products often store every plan change as a new row. To know what each user is on now, keep the newest row per user.

Write latest_plan(df) where df has columns user_id (int), plan (str) and updated_at (ISO timestamp string, so string order equals time order). Rows are in arbitrary order.

Return a DataFrame with the same columns, one row per user: the row with the largest updated_at. If two rows of a user share the largest updated_at, keep the one that appears LATER in the input. Sort the result by user_id ascending with a plain 0..n-1 index.

Signaturedef latest_plan(df)

Example

rows (1, 'free', '2026-01-01'), (1, 'pro', '2026-02-01'), (2, 'team', '2026-01-15') give user 1 'pro' and user 2 'team'.

Understand the idea

Billing tables often add a new row for every plan change, so to know a user's current plan you keep their newest row. The rows arrive in random order, so you must sort by time first. On an exact timestamp tie, the row that appears later in the input should win, which a stable sort preserves. Worked example: rows in this order: (1, 'pro', '2026-02-01'), (2, 'team', '2026-01-15'), (1, 'free', '2026-01-01'), (2, 'max', '2026-01-15'). For user 1 the newest is 'pro' even though it came first in the file. For user 2 both rows share the date, so the later row 'max' wins. Result: user 1 'pro', user 2 'max'. Rule: stable sort by updated_at (ISO strings sort like time), keep the last row per user_id, then sort by user_id and reset to a plain 0 to n-1 index, keeping the same columns. Dropping duplicates without sorting keeps whatever came last in the file, which may be an old row. Used to build current-state snapshots from change logs.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplelatest_plan(_d1()).to_dict('list')
  • Sample 2: unsorted historylatest_plan(_d2()).to_dict('list')
  • Test 3: tie keeps later rowlatest_plan(_d3()).to_dict('list')