Pandas DataFrame explode() method with examples

Spread the love

The explode() method in pandas transform each element in a list to a row in a DataFrame. If the array-like is empty, a missing value (NaN) will be placed for that row.

Syntax –

DataFrame.explode(column, ignore_index=False)

column – The label of the columns to unwrap.

ignore_index – If True, the resulting index will be labeled 0, 1, …, n – 1. By default it is False.

Examples –

Let’s create a dataframe to work with.

import pandas as pd

df = pd.DataFrame({'A':[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
                  'B':[10, 20, 30],
                  'C':[['a','b','c'], ['d','e','f'], ['g','h','i']]})

1 . Single Column Explode –

Let’s say you want to explode the A column. You want to turn every elements of the lists in A to a row. To do that you can use the explode() method in pandas.


2 . Multi-Column Explode –

You can also explode multiple columns together using the explode method in pandas. Let’s say you want to explode both the column A and C.


3 . Resetting the Index after explode –

To reset the index after explode set the ignore_index parameter to True.

df.explode(list('AC'), ignore_index=True)

Rating: 1 out of 5.

Leave a Reply