.explode()
In Pandas, the .explode()
method transforms each element of a list-like column (such as lists, tuples, or arrays) into separate rows, while replicating the corresponding index values. This is especially helpful when working with columns that contain nested or iterable data that needs to be flattened for further analysis.
Syntax
DataFrame.explode(column, ignore_index=False)
Parameters:
column
(string or tuple): Specifies the name of the column to explode. The column must contain list-like elements such as lists, tuples, or arrays.ignore_index
(Optional): If set toTrue
, the resulting DataFrame will have a new integer index ranging from0
ton - 1
. IfFalse
, the original index labels are retained and repeated as necessary.
Return value:
The .explode()
method returns a new DataFrame in which each element of the specified list-like column is expanded into a separate row. Values in other columns are duplicated accordingly to align with the exploded rows.
Example
The example below shows how to expand a column containing lists into multiple rows:
import pandas as pddf = pd.DataFrame({'Name': ['Alice', 'Bob'],'Hobbies': [['Reading', 'Cycling'], ['Painting']]})exploded_df = df.explode('Hobbies')print(exploded_df)
A possible output of this code is:
Name Hobbies0 Alice Reading0 Alice Cycling1 Bob Painting
The code takes the Hobbies
column, which contains lists, and creates one row for each item in the list, while preserving the associated values in the Name
column.
Codebyte Example
In this codebyte example, a column is exploded with tuple values:
Tuples are also treated as list-like by .explode()
.
Notes:
.explode()
is available in Pandas version 0.25.0 and later.- Cells with non-list-like values (e.g., strings, numbers) are not exploded and appear as-is in the resulting DataFrame.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:Pandas on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours