How to Use explode in pandas: Simple Guide with Examples
Use the
explode() method in pandas to transform each element of a list-like column into a separate row, duplicating the other column values. This is useful when you have columns with lists and want to flatten them into multiple rows for easier analysis.Syntax
The basic syntax of explode() is:
DataFrame.explode(column, ignore_index=False)
Where:
column: The name of the column to explode (must contain list-like data).ignore_index: IfTrue, resets the index in the result; default isFalse.
python
df.explode(column, ignore_index=False)Example
This example shows how to use explode() to convert a column of lists into multiple rows, duplicating other columns.
python
import pandas as pd data = {'Name': ['Alice', 'Bob'], 'Hobbies': [['Reading', 'Swimming'], ['Cycling']]} df = pd.DataFrame(data) exploded_df = df.explode('Hobbies', ignore_index=True) print(exploded_df)
Output
Name Hobbies
0 Alice Reading
1 Alice Swimming
2 Bob Cycling
Common Pitfalls
Common mistakes when using explode() include:
- Trying to explode a column that does not contain list-like data, which raises an error.
- Not resetting the index after exploding, which can cause confusing row labels.
- Exploding columns with empty lists or
NaNvalues, which behave differently (empty lists produce no rows,NaNstays as is).
python
import pandas as pd data = {'Name': ['Alice', 'Bob'], 'Hobbies': ['Reading', 'Cycling']} df = pd.DataFrame(data) # Wrong: Exploding a non-list column raises an error # df.explode('Hobbies') # This will raise an error # Right: Make sure the column contains lists df['Hobbies'] = df['Hobbies'].apply(lambda x: [x]) exploded_df = df.explode('Hobbies', ignore_index=True) print(exploded_df)
Output
Name Hobbies
0 Alice Reading
1 Bob Cycling
Quick Reference
| Parameter | Description | Default |
|---|---|---|
| column | Name of the column to explode (list-like) | Required |
| ignore_index | Reset index after exploding | False |
Key Takeaways
Use
explode() to turn list-like column elements into separate rows.Ensure the column contains lists or tuples before exploding to avoid errors.
Use
ignore_index=True to reset the index after exploding for cleaner output.Empty lists in the column result in no rows for that entry;
NaN values remain unchanged.Exploding helps flatten nested data for easier analysis and visualization.