pandas explode

The problem of pandas explode 

In this blog post, we will learn how one can explode the data frame in the pandas library of python. This problem is also known as pandas explode. An example of the above problem is shown here. The code for the same is:

 

 

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

df

Out[458]:


A     B

0 1 [1, 2]

1 2 [1, 2]

 

 

The expected output for the above code is also shown below:

 

 

A B

0 1 1

1 1 2

3 2 1

4 2 2

 

 

Solution

We are aware that object dtype columns make it difficult to use pandas functions to convert the data. The first thought that came to mind when we received this kind of data was to “flatten” or unnest the columns.

One of the methods is to explode only one column of the data frame in pandas is shown below:

 

 

df.explode('B')

 

The output for the above code is:

 

 

A data frame with a NaN or an empty list as the column value While an empty list won’t be problematic, a NaN must be supplied with a list.

Another method can be recreate your dataframe by using the repeat with DataFrame function Object() { [native code] }.

 

 

In the above code, one can notice that the output is the values of the different columns in the given dataset which too in multiple rows. 

 

 

Also Read: rmarkdown figure auto-adjust HTML

 

 

Share this post

One thought on “pandas explode

Leave a Reply

Your email address will not be published. Required fields are marked *