Keep the latest reading per sensor and day in pandas
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Given a pandas DataFrame with columns `['sensor', 'day', 'ts', 'reading']`, where `ts` is `datetime64[ns]`, implement `latest_reading_per_sensor_day(df)`. Collapse each `(sensor, day)` key to the single row with the most recent `ts`.
Requirements:
- Sort by `ts` ascending, then call `drop_duplicates(subset=['sensor', 'day'], keep='last')`.
- Sort the result by `['sensor', 'day']` ascending and reset the index to `0..n-1`.
- Return all four columns: `sensor`, `day`, `ts`, `reading`.
- Do not mutate the input. Return a new frame.
Example input:
```text
sensor day ts reading
A 2026-01-01 2026-01-01 08:00:00 10
A 2026-01-01 2026-01-01 12:00:00 15
B 2026-01-01 2026-01-01 09:00:00 20
```
Expected output:
```text
sensor day ts reading
0 A 2026-01-01 2026-01-01 12:00:00 15
1 B 2026-01-01 2026-01-01 09:00:00 20
```
Sensor A has two readings on 2026-01-01 and the 12:00 one is later, so it is the one kept. Sensor B has a single reading that day.
```hint What keep='last' depends on
`drop_duplicates` keeps the last row of each key in the frame's current row order. Think about what that order has to be before the call, and what the index looks like afterward.
```
### Constraints & Assumptions
- Every `ts` value in the test data is distinct, so each `(sensor, day)` key has exactly one latest row.
- `ts` is `datetime64[ns]`, and `day` is given as its own column.
- The caller's frame must come back unchanged.
### What a Strong Answer Covers
- Ordering the rows before deduplication so that `keep='last'` picks the latest timestamp within each key.
- Deduplicating on the composite `(sensor, day)` key.
- A deterministic output order and a clean `0..n-1` index.
- No mutation of the input, and exactly the four requested columns.
- What would break the approach: tied timestamps, missing `ts` values, an unstable sort.
### Follow-up Questions
- How would you break ties if two rows in the same `(sensor, day)` shared the same `ts`?
- Would `groupby(...).tail(1)` or `idxmax` be a better approach on a large frame, and what does each one assume?
- What changes if some `ts` values are missing (`NaT`)?
- How would you write the same deduplication in SQL?
Overview: Implement a pandas function that keeps only the most recent reading for each sensor and day. It tests sorting before drop_duplicates, deduplication on a composite key, resetting the index, and handling of tied or missing timestamps.