0

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
1
  • 2
    the explode method is the answer df.explode(df.columns.to_list()) Commented Aug 2, 2022 at 9:25

4 Answers 4

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Sreeram. Appreciate your quick help.
1

try:

df.explode(df.columns.to_list())

Comments

0
df.explode('C').explode(['A', 'B'])

Comments

0
df.apply(pd.Series.explode).reset_index()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.