Drop duplicate orders, keeping the latest row per order_id
df has one row per order update, columns order_id, status, updated_at. Some order_id values repeat. Return one row per order_id — the most recent by updated_at.
import pandas as pd
def latest_orders(df: pd.DataFrame) -> pd.DataFrame:
# your code here
Write the implementation.
Sort by the timestamp, then drop duplicates keeping the last row per key: df.sort_values('updated_at').drop_duplicates('order_id', keep='last'). The sort is what makes keep='last' mean newest; without it you keep whichever row happened to sit last in file order, not the latest update.
- ✗Calling drop_duplicates without sorting first, so keep='last' is arbitrary
- ✗Sorting by order_id instead of by updated_at
- ✗Using keep='first' after a descending sort by mistake
- →How would you keep the latest row using groupby and idxmax instead?
- →What happens to ties where two rows share the same updated_at?
Sort by updated_at so the newest row sits last per key, then drop duplicates with keep='last'.
import pandas as pd
def latest_orders(df: pd.DataFrame) -> pd.DataFrame:
return (df.sort_values('updated_at')
.drop_duplicates('order_id', keep='last')
.reset_index(drop=True))
The sort is the load-bearing step — keep='last' only means "newest" once rows are in time order. An equivalent is df.loc[df.groupby('order_id')['updated_at'].idxmax()], which picks the max-timestamp row per group without a full sort.