Flag every row with a duplicated order_id in a pandas DataFrame
Quick Overview
Write a pandas function that returns a copy of a DataFrame with a trailing boolean column flagging every row whose order_id appears more than once, first occurrence included. It tests duplicate detection options, not mutating the input, and keeping the original index.
Flag every row with a duplicated order_id in a pandas DataFrame
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `add_is_duplicate_flag(df)`, which returns a copy of `df` plus a boolean column `is_duplicate` marking rows whose `order_id` appears more than once.
```python
import pandas as pd
def add_is_duplicate_flag(df: pd.DataFrame) -> pd.DataFrame:
...
```
For example:
```python
df = pd.DataFrame({"order_id": [1, 2, 2, 3]}, index=[10, 11, 12, 13])
add_is_duplicate_flag(df)["is_duplicate"].tolist()
# [False, True, True, False]
```
Order 2 appears twice, so both of its rows are flagged, while orders 1 and 3 appear once.
```hint Which rows count
Every row in a repeated `order_id` group gets flagged, the first occurrence included. Check how pandas' duplicate detection decides which occurrence to leave unflagged, and whether you can turn that off.
```
### Constraints & Assumptions
- Flag every duplicated row, first occurrence included.
- Keep all original columns unchanged and append `is_duplicate` as the last column.
- Preserve the original index. Do not call `reset_index()`.
- Do not mutate the input `df`.
### What a Strong Answer Covers
- Flagging all members of a duplicated group, including the first occurrence.
- Working on a copy so the caller's DataFrame is unchanged.
- Adding the flag as the trailing column while keeping the original index and row order.
- The time and space cost of the approach.
### Follow-up Questions
- How would you flag duplicates on a composite key like `(order_id, sku)`?
- How does `keep=False` differ from `keep='first'`?
- How are missing `order_id` values treated, and is that the behavior you want?
Overview: Write a pandas function that returns a copy of a DataFrame with a trailing boolean column flagging every row whose order_id appears more than once, first occurrence included. It tests duplicate detection options, not mutating the input, and keeping the original index.