close

How to unnest (explode) a column in a pandas DataFrame?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to unnest (explode) a column in a pandas DataFrame in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to unnest (explode) a column in a pandas DataFrame?

  1. How to unnest (explode) a column in a pandas DataFrame?

    Exploding a list-like column has been simplified significantly in pandas 0.25 with the addition of the explode() method:

  2. unnest (explode) a column in a pandas DataFrame

    Exploding a list-like column has been simplified significantly in pandas 0.25 with the addition of the explode() method:

Method 1

Exploding a list-like column has been simplified significantly in pandas 0.25 with the addition of the explode() method:

df = pd.DataFrame({'A': [1, 2], 'B': [[1, 2], [1, 2]]})
df.explode('B')

Out:

   A  B
0  1  1
0  1  2
1  2  1
1  2  2

Method 2

df=pd.DataFrame({'A':[1,2],'B':[[1,2],[1,2]]})

pd.concat([df['A'], pd.DataFrame(df['B'].values.tolist())], axis = 1)\
  .melt(id_vars = 'A', value_name = 'B')\
  .dropna()\
  .drop('variable', axis = 1)

    A   B
0   1   1
1   2   1
2   1   2
3   2   2

Any opinions on this method I thought of? or is doing both concat and melt considered too “expensive”?

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read