Explode a pandas list column into one row per element
Quick Overview
Write a pandas function that turns a column of Python lists into one row per list element while repeating the user value on each row. It tests list unnesting in pandas, resetting the index after rows multiply, and handling empty lists.
Explode a pandas list column into one row per element
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `explode_tags(df)`. The input DataFrame has columns `['user', 'tags']`, where each `'tags'` value is a Python list. Return one row per list element, with the `'user'` value repeated on each of those rows.
```python
def explode_tags(df: pd.DataFrame) -> pd.DataFrame:
...
```
The result must meet these requirements:
- The output keeps columns `['user', 'tags']`, with each `'tags'` value a scalar string.
- The index is a fresh default `RangeIndex` (`0..n-1`).
- An empty list becomes a single row with `NaN` in `'tags'`.
Example:
```python
df = pd.DataFrame({
"user": ["u1", "u2", "u3"],
"tags": [["a", "b"], ["c"], []],
})
explode_tags(df)
# user tags
# 0 u1 a
# 1 u1 b
# 2 u2 c
# 3 u3 NaN
```
```hint Where to look
Pandas has a built-in DataFrame method for unnesting list-like cells. Once you find it, check which index labels the new rows get.
```
### What a Strong Answer Covers
- How each tag stays paired with the right `user` after unnesting.
- What happens to the index labels when one input row becomes several output rows, and how the result ends up with a clean `RangeIndex`.
- The empty-list case, and what the code does with `NaN` or `None` in `'tags'`.
- Time and memory cost in terms of the total number of tags, compared with a Python loop over rows.
### Follow-up Questions
- How does `DataFrame.explode` handle empty lists by default?
- How would you drop users with empty lists instead of keeping a `NaN` row for them?
- How would you explode two list columns, such as `tags` and `scores`, whose elements line up position by position?
- How would you collapse the exploded frame back into one list per user?
Overview: Write a pandas function that turns a column of Python lists into one row per list element while repeating the user value on each row. It tests list unnesting in pandas, resetting the index after rows multiply, and handling empty lists.
Implement explode_tags(df). The input DataFrame has columns ['user', 'tags'], where each 'tags' value is a Python list. Return one row per list element, with the 'user' value repeated on each of those rows.