Add a Combined Validity Flag Column to a pandas DataFrame
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `add_validity_flag(df: pd.DataFrame) -> pd.DataFrame`. The input has columns `['txn_id', 'amount', 'currency']` with types int, float and str. Append a column `is_valid` that is `True` when `amount > 0` and `currency` is in `{'USD', 'EUR', 'GBP'}`, and `False` otherwise.
The function must:
- Keep every original row. Do not filter.
- Keep the original columns in their order, with `is_valid` appended last.
- Leave the index unchanged.
- Store `is_valid` as a boolean dtype, not as strings.
Example:
```python
df = pd.DataFrame({
'txn_id': [1, 2, 3],
'amount': [10.0, -5.0, 20.0],
'currency': ['USD', 'EUR', 'JPY'],
})
add_validity_flag(df)
# txn_id amount currency is_valid
# 0 1 10.0 USD True
# 1 2 -5.0 EUR False # amount <= 0
# 2 3 20.0 JPY False # currency not allowed
```
```hint Evaluate every row at once
Each rule can be written as a boolean Series over a whole column. Before you combine two of them, check how Python's `&` binds relative to `>`.
```
### What a Strong Answer Covers
- How each rule is evaluated for all rows without a Python loop, and how the two results are combined.
- Why the output keeps every row, the original column order and the index.
- The dtype of `is_valid` and how the answer guarantees it is boolean.
- What happens to rows where `amount` or `currency` is missing.
- Whether the function modifies the caller's DataFrame.
### Follow-up Questions
- How would you record which rule failed for each row instead of a single flag?
- How would you handle NaN in `amount` or `currency`, and how would you make that behavior explicit?
- Some currency values arrive as `'usd'` or `'USD '`. How would you change the function, and what would you check before changing it?
Overview: Write a pandas function that appends a boolean is_valid column to a transactions DataFrame, flagging rows that have a positive amount and an allowed currency code. It tests vectorized boolean logic, dtype control, missing-value behavior, and keeping every row, the column order and the index intact.