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

Question:

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
Asked By: Ranjana Jha

||

Answers:

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)
Answered By: Sreeram TP

try:

df.explode(df.columns.to_list())
Answered By: 99_m4n
df.explode('C').explode(['A', 'B'])
Answered By: ArrowRise
df.apply(pd.Series.explode).reset_index()
Answered By: David Molina
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.