List column to rows
Pandas data engineering interview problem. Difficulty: beginner. Pattern: Filtering. About 10 minutes. Free to practice.
Turn a comma-separated string column into one trimmed row per value. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.
Many tables store several values in one text column, separated by commas, for example a, b ,c. To work with them, you want 1 row for each value. The text can be messy: spaces around the values, empty pieces like x,,y, or a missing value. df has id and tags. Return 1 row for each id and tag, with the spaces around each tag removed. Do not return empty or missing tags. Return id and tag, keep the original order of the ids and of the tags inside each id, and reset the index. The editor builds df and ends with result = df. Change the last line. Split the text, explode the lists, strip the spaces and filter.
Requirements
- Split tags on commas and use explode to get 1 row for each piece.
- Remove the spaces around each tag with str.strip().
- Drop tags that are missing or empty.
- Return id and tag with a clean index in result.
Constraints
- Keep the order of ids and the order of tags inside each id. Do not sort.
- A missing tags value gives a missing tag after explode, which must be removed.
- Strip before you test for empty, because a tag with only spaces becomes empty after stripping.
Examples
Input: df id | tags 1 | a, b ,c 2 | 3 | NULL 4 | red ,blue 5 | x,,y Output: id | tag 1 | a 1 | b 1 | c 4 | red 4 | blue 5 | x 5 | y Ticket 1 gives a, b and c. Row 2 (spaces only) and row 3 (missing) give nothing; 4 gives red and blue; 5 gives x and y.
Topics: lakebench, pandas, str.split, explode, strip.
More interview problems · All interview problems · Learn data engineering
List column to rows
Interview-style drill: Turn a comma-separated string column into one trimmed row per value.
`df` has `id` and `tags`, a comma-separated string such as `'a, b ,c'`. Values can have spaces around them, be empty (`'x,,y'`), or be missing entirely. Return 1 row per `id` and tag with the spaces removed. Empty and missing tags are not returned. Columns: `id`, `tag`. Keep the original order of ids and of tags inside each id, and reset the index. Assign the DataFrame to `result`.