Pandas DataFrame explode() Method
In this tutorial, we will learn the Python pandas DataFrame.explode()
method. It transforms each element of a list-like to a row, replicating index values. It returns DataFrame exploded lists to rows of the subset columns; index will be duplicated for these rows.
The below shows the syntax of the DataFrame.explode()
method.
Syntax
DataFrame.explode(column, ignore_index=False)
Parameters
column: str or tuple. Column to explode.
ignore_index: bool, default False. If True, the resulting index will be labeled 0, 1, …, n - 1.
Example 1: Explode DataFrame using the DataFrame.explode()
Method
If some of the elements in the column of the DataFrame consist of lists, we can expand that to multiple columns using the DataFrame.explode()
method. The below example shows the same.
#importing pandas as pd
import pandas as pd
df = pd.DataFrame({'A': [[1,3],[3]], 'B': 1})
print("------The DataFrame is--------")
print(df)
print("After expanding the DataFrame")
print(df.explode('A'))
Once we run the program we will get the following output.
------The DataFrame is--------
A B
0 [1, 3] 1
1 [3] 1
After expanding the DataFrame
A B
0 1 1
0 3 1
1 3 1
Example 2: Explode DataFrame using the DataFrame.explode()
Method
This example is similar to the previous example, just we used the ignore_index=True
parameter, the resulting index will be labeled 0, 1, …, n - 1.
#importing pandas as pd
import pandas as pd
df = pd.DataFrame({'A': [[1,3],[4]], 'B': 1})
print("------The DataFrame is--------")
print(df)
print("After expanding the DataFrame")
print(df.explode('A',ignore_index=True))
Once we run the program we will get the following output.
------The DataFrame is--------
A B
0 [1, 3] 1
1 [4] 1
After expanding the DataFrame
A B
0 1 1
1 3 1
2 4 1
Example 3: Explode DataFrame using the DataFrame.explode()
Method
This example is similar to the previous example. The empty lists will be expanded into a numpy.nan
value.
#importing pandas as pd
import pandas as pd
df = pd.DataFrame({'A': [[1, 2], []], 'B': 1})
print("------The DataFrame is--------")
print(df)
print("After expanding the DataFrame")
print(df.explode('A',ignore_index=True))
Once we run the program we will get the following output.
------The DataFrame is--------
A B
0 [1, 2] 1
1 [] 1
After expanding the DataFrame
A B
0 1 1
1 2 1
2 NaN 1
Conclusion
In this tutorial, we learned the Python pandas DataFrame.explode()
method. We learned syntax, parameters, and solved examples by applying this method on the DataFrame consisting of the lists as elements.