How to unnest (explode) a row in a pandas series?


If some of the elements in the series object have lists, then we can unnest those list elements into multiple rows of the series object. Unnesting is nothing but exploding the lists into rows.

So this transformation can be done easily with the help of the pandas series.explode() method. This method is used to transform list-like elements of a series object into rows, and the index will be duplicated for these rows.

The ignore_index is the only parameter for this method and it takes boolean values, False is the default one, and True means the resulting index will be labeled from 0 to n - 1.

Example 1

In the following example, we will see how the series.explode() method transforms the list-like elements of the series object into rows.

# importing pandas package
import pandas as pd

# create a nested list
L = [1, 2, [4, 8, 9, 2], [], ["a", "b", "c"]]

# Create a pandas series using the list
series = pd.Series(L)

# unnest the series using explode() method
result = series.explode()

print("Original Series:")
print(series)

print("Result:", result)

Explanation

Here we have created a series object with a python nested list and then applied the explode() method.

Output

The output is given below −

Original Series:
0              1
1              2
2    [4, 8, 9, 2]
3              []
4       [a, b, c]
dtype: object

Result:
0    1
1    2
2    4
2    8
2    9
2    2
3  Nan
4    a
4    b
4    c
dtype: object

In the above output block, we can notice that the elements 4, 8, 9, 2 are transformed into new rows of the resultant series object. Moreover, there is an empty list-like element at index position 3 and the resultant row will have np.nan for that position 3.

Example 2

In the following example, we will see how the series.explode() method transforms the elements like list, tuple objects of the series into rows.

# importing pandas package
import pandas as pd

# Create a pandas series
series = pd.Series([(0, 1, 2,), list("xyz"), (5, 6, 7)])

# unnest the series using explode() method
result = series.explode()

print("Original Series:")
print(series)

print("Result:", result)

Explanation

Initially, we created a series object with a python list of 3 elements (tuple, list) and then applied the explode() method.

Output

The output is given below −

Original Series:
0    (0, 1, 2)
1    [x, y, z]
2    (5, 6, 7)
dtype: object

Result:
0    0
0    1
0    2
1    x
1    y
1    z
2    5
2    6
2    7
dtype: object

In the above output block, we can notice that the elements of series objects are successfully transformed into new rows of the resultant series object.

Updated on: 07-Mar-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements