1

I have below data frame using pandas library

import pandas as pd
import numpy as np

dat = pd.concat([pd.DataFrame({'X' : 1, 'Y' : [[1,2]], 'Z' : [['A', 'B']]}), pd.DataFrame({'X' : 11, 'Y' : [[11,21,31]], 'Z' : [['AA', 'BB', 'CC']]})], axis = 0)
     X             Y               Z
0    1        [1, 2]          [A, B]
0   11  [11, 21, 31]    [AA, BB, CC]

Now I want to convert dat into below shape

print(pd.DataFrame({'X' : [1,1,11,11,11], 'Y' : [1,2,11,21,31], 'Z' : ['A', 'B', 'AA', 'BB', 'CC']}))
    X   Y   Z
0   1   1   A
1   1   2   B
2  11  11  AA
3  11  21  BB
4  11  31  CC

Is there any direct method/function available to perform the same?

AlexK
  • 2,855
  • 9
  • 16
  • 27
Bogaso
  • 2,838
  • 3
  • 24
  • 54

1 Answers1

0

Use the .explode() method:

res = dat.set_index('X').explode(['Y','Z']).reset_index()

print(res)
#   X   Y   Z
# 0 1   1   A
# 1 1   2   B
# 2 11  11  AA
# 3 11  21  BB
# 4 11  31  CC
AlexK
  • 2,855
  • 9
  • 16
  • 27