Filter pandas DataFrame rows whose column value is in a list (SQL IN with isin)
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `filter_in(df, col, values)` that returns every row of `df` whose value in column `col` appears in the list `values`. This is the pandas equivalent of SQL `IN`, built with an `.isin` mask.
Requirements:
- Return only the rows where `df[col]` is one of the entries in `values`.
- Keep all columns unchanged.
- Preserve the original index and row order.
Example:
```python
df = pd.DataFrame({
'team': ['A', 'B', 'C', 'A'],
'pts': [10, 20, 30, 40],
})
filter_in(df, 'team', ['A', 'C'])
# team pts
# 0 A 10
# 2 C 30
# 3 A 40
```
```hint Check the missing values
Consider a row where `col` is missing. Decide what your function returns for it, and compare that with how SQL treats `NULL` in an `IN` list.
```
### What a Strong Answer Covers
- Builds one boolean mask with `.isin` and selects rows with it, keeping every column.
- Explains why boolean indexing keeps the original index labels and row order without a sort or reset.
- States how missing values in `col` and in `values` are handled, and where that differs from SQL `IN`.
- Compares the cost of the hashed membership test with chaining one equality comparison per value.
- Mentions input pitfalls such as an empty `values` list or values whose type does not match the column.
### Follow-up Questions
- How would you invert the filter to keep the rows whose value is not in `values`? Does the result match SQL `NOT IN` when the column has missing values?
- How would you filter on membership of a pair of columns, for example a list of allowed `(team, season)` tuples?
- The column holds integers but `values` arrives as strings such as `['1', '2']`. What happens, and how would you guard against it?
Overview: Write a pandas function that keeps the DataFrame rows whose value in one column appears in a given list, the equivalent of SQL IN. It tests boolean masks with isin, keeping the index and row order, and how missing values differ between pandas and SQL IN and NOT IN.