The explode()
method in Pandas is used to transform each element of a list-like element to a row, replicating the index values.
Example
import pandas as pd
# sample DataFrame
data = {'A': [[1, 2], [3, 4], [5]],
'B': ['X', 'Y', 'Z']}
df = pd.DataFrame(data)
# use explode on column A
exploded_df = df.explode('A')
print(exploded_df)
'''
Output
A B
0 1 X
0 2 X
1 3 Y
1 4 Y
2 5 Z
'''
explode() Syntax
The syntax of the explode()
method in Pandas is:
df.explode(column, ignore_index=False)
explode() Arguments
The explode()
method has the following arguments:
column
: specifies the column to explodeignore_index
(optional): if True, the resulting index will reset.
explode() Return Value
The explode()
method returns a DataFrame with the same columns as the input DataFrame, but rows are expanded as per list-like entries in the specified column.
Example 1: Basic Explode
import pandas as pd
data = {'Names': [['Alice', 'Bob'], ['Cindy', 'Dan']]}
df = pd.DataFrame(data)
# explode the 'Names' column
exploded_names = df.explode('Names')
print(exploded_names)
Output
Names 0 Alice 0 Bob 1 Cindy 1 Dan
In this example, we exploded the Names
column to separate each list into individual rows.
Example 2: Explode with Index Reset
import pandas as pd
data = {'Names': [['Alice', 'Bob'], ['Cindy', 'Dan']]}
df = pd.DataFrame(data)
# explode the 'Names' column
exploded_names = df.explode('Names', ignore_index=True)
print(exploded_names)
Output
Names 0 Alice 1 Bob 2 Cindy 3 Dan
In this example, we exploded the Names
column and reset the index using ignore_index=True
.