2

I have:

df = pd.DataFrame(
    {
     "A": [["a", "b", "c"], ["d"]], 
     "B": [[1, 2, 3], [4]], 
     "C": [["abc"], ["def"]]
    }
)
     A          B           C
0   [a, b, c]   [1, 2, 3]   [abc]
1   [d]         [4]         [def]

My expected output is:

   A  B  C
0  a  1  abc
1  b  2  abc
2  c  3  abc
3  d  4  def

I tried it with

df = df.explode("A")
df = df.explode("B")

But it creates a "combinatoric product" and keep the Index.

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
Mars
  • 41
  • 6
  • A [similar question](https://stackoverflow.com/questions/62702642/explode-multiple-columns-into-rows-maintaining-single-list-elements-order-pandas) was closed. – Mykola Zotko Oct 20 '20 at 11:14

2 Answers2

5

You can use df.apply with pd.Series.explode

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

   A  B    C
0  a  1  abc
0  b  2  abc
0  c  3  abc
1  d  4  def
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
2

There may be a simpler solution is out there, but you can try this for now

newdf=df.explode("A")
newdf['B'] = df.explode("B")['B']
newdf['C'] = newdf['C'].str[0]
newdf.reset_index(drop=True)

output

    A   B   C
0   a   1   abc
1   b   2   abc
2   c   3   abc
3   d   4   def
moys
  • 7,747
  • 2
  • 11
  • 42