pandas · difficulty ◆◆
pandas explode() — one row per element, no for loop
Split the cell, explode the list, then group — the whole multi-value-column workflow is three chained calls.
Your ERP export has one row per order and a single cell holding six part numbers. Your report needs one row per part. This is the method that gets you there.
fully AI-generatedThis text is fully AI-generated and was published without human editorial review.$ df.explode()- 0.25.0
- Introduced
- 1.1.0
- ignore_index added
- 1.3.0
- Multi-column explode
- 2
- Parameters
whatsnew v0.25.0 (July 18, 2019): Series.explode + DataFrame.explode
whatsnew v1.1.0, GH 34932
whatsnew v1.3.0, GH 39240
DataFrame.explode(column, ignore_index) — the complete signature in pandas 3.0
What it does
explode() takes a column whose cells are list-likes — lists, tuples, ndarrays, even sets — and turns each element into its own row, copying the rest of that row's columns. DataFrame.explode('col') handles one column; pass a list of names and it explodes several in lockstep, pairing values by position. ignore_index=True renumbers the result 0..n-1 instead of repeating parent labels.
Why it matters
A lot of real data arrives wide and packed: tags, part numbers, recipients, per-line quantities. As long as they sit in one cell, groupby cannot count them, merge cannot join them, and plotting treats the whole cell as one category. explode is the bridge between 'what the source system sent' and 'what pandas can aggregate' — the unpivot you reach for when the repeated thing is inside a cell rather than across columns.
Example
$ import pandas as pd
tickets = pd.DataFrame({
"ticket": ["T-101", "T-102", "T-103"],
"team": ["Field Service", "Spares", "Field Service"],
"labels": [["valve", "leak"], ["delivery"], ["valve", "warranty", "leak"]],
})
print(tickets.explode("labels")) ticket team labels
0 T-101 Field Service valve
0 T-101 Field Service leak
1 T-102 Spares delivery
2 T-103 Field Service valve
2 T-103 Field Service warranty
2 T-103 Field Service leakOne row per label, and every other column rides along. Look at the index: 0, 0, 1, 2, 2, 2 — the parent row's label is repeated, not renumbered.
$ import pandas as pd
orders = pd.DataFrame({
"order": ["PO-9001", "PO-9002"],
"item": [["ball valve", "gasket"], ["pressure sensor"]],
"qty": [[4, 10], [2]],
})
print(orders.explode(["item", "qty"], ignore_index=True)) order item qty
0 PO-9001 ball valve 4
1 PO-9001 gasket 10
2 PO-9002 pressure sensor 2Two columns at once pairs them positionally: ball valve keeps 4 and gasket keeps 10. ignore_index=True gives you a clean 0..n-1 index for the next step.
$ import pandas as pd
log = pd.DataFrame({
"asset": ["P-101", "P-102", "P-103"],
"parts": ["seal; bearing", "bearing", "seal; gasket; bearing"],
})
used = log.assign(parts=log["parts"].str.split("; ")).explode("parts")
print(used.groupby("parts")["asset"].count().sort_values(ascending=False))parts
bearing 3
seal 2
gasket 1
Name: asset, dtype: int64The everyday chain: split the delimited cell into a list, explode it, then group. A semicolon-separated ERP export becomes a parts-usage report in three calls.
$ import pandas as pd
rfq = pd.DataFrame({"rfq": ["RFQ-1", "RFQ-2"], "bidders": [[], ["ACME", "Delta"]]})
print(rfq.explode("bidders"))
print("---")
print(rfq.explode("bidders").dropna(subset=["bidders"])) rfq bidders
0 RFQ-1 NaN
1 RFQ-2 ACME
1 RFQ-2 Delta
---
rfq bidders
1 RFQ-2 ACME
1 RFQ-2 DeltaAn empty list does not vanish: it becomes one NaN row. Drop it when an empty list means 'no bids', keep it when it means 'unknown' — but decide on purpose.
Common flags
- column='col'
- A single column name, or a list of names to explode several columns at once.
- ignore_index=False
- Default repeats the parent's index label on every produced row; True gives a fresh 0..n-1 index.
- df.explode(['a', 'b'])
- Multi-column mode pairs row-wise positionally — a[0] with b[0], a[1] with b[1]. Lengths must match per row.
- s.explode()
- Series form: no column argument, same rules, returns a Series with a repeated index.
- list, tuple, set, ndarray
- All accepted as list-likes. Sets give non-deterministic row order — documented, not a bug.
- scalars pass through
- A cell that is not list-like (a plain string, a number) is returned unchanged, one row, no error.
- empty list → NaN
- An empty list-like produces a single NaN row; it never disappears silently.
History
0.25.0, July 18 2019
Series.explode and DataFrame.explode shipped in the same release, closing a request that had been open for years (GH 10511, GH 16538). The whatsnew entry showed the idiom that is still the canonical one: df.assign(var1=df.var1.str.split(',')).explode('var1'). Before that, people rebuilt these frames with itertuples and append, or with numpy.repeat by hand.
It grew into a reshaping verb
The first version could only explode one column. ignore_index arrived in 1.1.0 (GH 34932) because everyone was chaining .reset_index(drop=True) anyway, and multi-column explode came in 1.3.0 (GH 39240). It now lives in pandas' reshape namespace next to melt and stack — same job, different starting shape: melt unpacks columns, explode unpacks cells.
Under the hood
Under the hood: index.repeat plus a Cython gather
Series.explode delegates to pandas._libs.reshape.explode (compiled Cython), which walks the object array once and returns two things: the flattened values and a counts array of element counts per cell. The exploded index is then literally self.index.repeat(counts) — that is where the duplicate labels come from — and ignore_index just swaps in a fresh RangeIndex. If the dtype is not object and not an extension array, the whole call short-circuits to a copy. DataFrame.explode resets its index to 0..n-1 first, explodes the requested columns, joins the untouched columns back on that positional index, and finally restores the original labels with self.index.take(result.index). Multi-column mode checks lengths with a helper that counts an empty list as 1, then builds each column independently and requires the counts to agree — which is why mismatched lists raise 'columns must have matching element counts' instead of producing ragged output.
Fun facts
Pros & cons
pros
- + Replaces the itertuples-and-append loop that used to be the answer, and keeps every sibling column without a manual merge.
- + Multi-column mode explodes paired values together, so quantities stay attached to their items.
- + Index handling is explicit: keep the parent labels to trace rows back, or ask for a clean one.
cons
- − Repeated index labels by default — the classic setup for silently misaligned assignment and confusing .loc lookups.
- − Exploded numeric lists come back dtype object (verified), so cast with astype before parquet writes or dtype assertions.
- − Multi-column mode is strictly positional: it cannot zip unequal lists, pad them, or combine them as a product of values.
Takeaways
- 1Split, then explode: df.assign(c=df['c'].str.split('; ')).explode('c') — never loop over rows for this.
- 2Pass ignore_index=True unless you specifically need the parent row's label to trace the child rows back.
- 3Multi-column explode pairs values positionally, so the lists in each row must be the same length or you get a ValueError.
- 4Empty lists become NaN rows — .dropna(subset=['c']) after exploding if an empty cell means 'nothing here'.
- 5Cast the exploded column back to a numeric dtype before writing parquet or asserting dtypes.
Related commands
archive entry — written and published by a scheduled job, never editorially reviewed. Kept for reference: out of the site’s search index, and no ads run here. the reviewed library →
