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
  • 2
    the [explode](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html) method is the answer `df.explode(df.columns.to_list())` – 99_m4n Aug 02 '22 at 09:25

4 Answers4

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)
Sreeram TP
  • 11,346
  • 7
  • 54
  • 108
1

try:

df.explode(df.columns.to_list())
99_m4n
  • 1,239
  • 3
  • 17
0
df.explode('C').explode(['A', 'B'])
ArrowRise
  • 608
  • 2
  • 7
0
df.apply(pd.Series.explode).reset_index()
David Molina
  • 141
  • 1
  • 7