Normalize nested list values
A table stores several labels, categories, or IDs in one cell and downstream processing needs one value per row.
Pandas · Module
Expands list-like values in one or more DataFrame columns into separate rows. Non-exploded columns are repeated, and the original index is retained unless you request a fresh one.
Call explode on one column or a list of columns to expand list-like values into separate rows. Other columns are repeated, the original index is retained by default, and ignore_index=True replaces it with a sequential index.
DataFrame.explode(column, ignore_index=False)| Name | Type | Description |
|---|---|---|
column | IndexLabel | Column or columns to expand. For multiple columns, use a non-empty list of strings or tuples, with equal list-like lengths across selected columns on each row. |
ignore_index | bool, default False | Whether to replace the original index with a sequential range from 0 to n - 1. |
DataFrame with list-like values expanded into rows; the selected subset has object dtype and the original index is duplicated unless ignore_index is True.
column to choose the single column or columns whose list-like values should be expanded.ignore_index=True when the result should receive a new zero-based sequential index.import pandas as pd
df = pd.DataFrame({
"id": [1, 2, 3],
"tags": [["red", "blue"], [], "green"],
})
result = df.explode("tags", ignore_index=True)
print(result)Each list element becomes its own row; the empty list produces a missing value, and ignore_index creates a fresh sequential index.
A table stores several labels, categories, or IDs in one cell and downstream processing needs one value per row.
Two related list columns must be expanded side by side while preserving element-to-element correspondence.
Expanded rows need a clean range index for export, joins, or positional processing.
explode converts each list-like element in the selected column into a separate row and repeats the other column values. By default, the source index is duplicated for the generated rows.
Follow-up: How would you preserve row alignment while expanding two columns? Pass both columns as a non-empty list and ensure their list-like values have matching lengths in every row.
The column argument accepts an IndexLabel identifying one column or multiple columns. For multiple columns, provide a non-empty list whose entries are strings or tuples.
Follow-up: What failure condition should you check before a multi-column explode? Every selected list-like group on the same row must have equal length.
ignore_index=False is the default, so generated rows retain duplicated original index labels. Setting it to True labels the result from zero through the number of rows minus one.
Follow-up: When would retaining the original index be useful? It preserves a direct reference to the source row for each expanded value.
pandas.DataFrame.unstackpandas.Series.explodepandas.DataFrame.stackpandas.DataFrame.melt