How does Pandas explode() Function work (With Examples)

The Pandas explode() function is used to transform a list, dict, or Series object into rows in a DataFrame. It takes each element of the list, dict, or Series object and creates a new row in the DataFrame with the element as the value. For example, if we have a list of fruits, the explode() function will create a separate row for each fruit in the list with the name of the fruit as the value. This is useful when dealing with multiple values that need to be represented in different rows so that they can be used for further analysis.


You can use the pandas function to transform each element in a list to a row in a DataFrame.

This function uses the following basic syntax:

df.explode('variable_to_explode')

The following example shows how to use this syntax in practice.

Example: Use explode() Function with Pandas DataFrame

Suppose we have the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']],
                   'position':['Guard', 'Forward', 'Center'],
                   'points': [7, 14, 19]})

#view DataFrame
df

	team	        position  points
0	[A, B, C]	Guard	  7
1	[D, E, F]	Forward	  14
2	[G, H, I]	Center	  19

Notice that the team column contains lists of team names.

We can use the explode() function to explode each element in each list into a row:

#explode team column
df.explode('team')

        team	position  points
0	A	Guard	  7
0	B	Guard	  7
0	C	Guard	  7
1	D	Forward	  14
1	E	Forward	  14
1	F	Forward	  14
2	G	Center	  19
2	H	Center	  19
2	I	Center	  19

Notice that the team column no longer contains lists. We “exploded” each element of each list into a row.

Also notice that some rows now have the same index value.

We can use the reset_index() function to reset the index when exploding the team column:

#explode team column and reset index of resulting dataFrame
df.explode('team').reset_index(drop=True)

	team	position  points
0	A	Guard	  7
1	B	Guard	  7
2	C	Guard	  7
3	D	Forward	  14
4	E	Forward	  14
5	F	Forward	  14
6	G	Center	  19
7	H	Center	  19
8	I	Center	  19

Notice that each row now has a unique index value.

x