Count prompts per tag by exploding a list column
Why it matters Tags, retrieved document ids and tool calls are often stored as lists per row, and explode is the standard way to analyse them.
Prompt datasets often store tags as a list per row. To count how many prompts carry each tag you first need one row per (prompt, tag), which is what explode does.
Write tag_counts(df) where df has columns prompt_id (int) and tags (a Python list of str, possibly empty, and a tag can be repeated by mistake inside one list).
Return a DataFrame with columns exactly [tag, n_prompts]: the number of DIFFERENT prompts that carry each tag. Prompts with an empty list contribute nothing. Sort by n_prompts descending, then tag ascending, plain 0..n-1 index.
def tag_counts(df)Example
prompt 1 tags ['math', 'code'], prompt 2 tags ['math'], prompt 3 tags [] gives tag ['math', 'code'], n_prompts [2, 1].
Understand the idea
explode turns a column of lists into one row per list element, copying the other columns. It is the pandas way to unnest data.
Worked example: prompt 1 has ['math', 'code'] and prompt 2 has ['math']. After explode: (1, math), (1, code), (2, math). Prompt 3 with [] becomes (3, NaN), which we drop. Counting distinct prompts per tag gives math = 2 and code = 1.
Rule: rows after explode = sum over rows of max(1, len(list)). Drop NaN for empty lists and deduplicate (id, element) if one id can repeat an element.
RAG logs (retrieved chunk ids per query), agent traces (tools called per step) and labeled datasets with multi-label tags all need this.