Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert dataframe columns with list of values into rows in Pandas DataFrame

i have a dataframe like this"

   A       B        C
0  [X]     [1]  [aa, bb, cc]
1  [Y]     [2]  [xx, yy]

i want to change it to:

   A       B        C
0  X       1        aa
1  X       1        bb
2  X       1        cc
3  Y       2        xx
4  Y       2        yy

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use explode method chained like this,

df.explode('A').explode('B').explode('C').reset_index(drop=True)


   A  B   C
0  X  1  aa
1  X  1  bb
2  X  1  cc
3  Y  2  xx
4  Y  2  yy

Alternatively, you can apply pd.Series.explode on the dataframe like this,

df.apply(pd.Series.explode).reset_index(drop=True)

In pandas 1.3+ you can use a list of columns to explode on,

So the code will look like,

df.explode(['A', 'B', 'C']).reset_index(drop=True)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading