1

In pandas, I want to change the data format as below. In my thought, I have only idea with reading line by line with open('filename') and parse after readline. Is there any way to to this in python pandas.

From

Column A Column B
A [1,2,3]
B [4,5,6]

to

Column A Column B
A 1
A 2
A 3
B 4
B 5
B 6
puhuk
  • 464
  • 5
  • 15

1 Answers1

1

use explode:

df = df.explode('Column B')

Another way via list comprehension:

d = {'Column A': {0: 'A', 1: 'B'}, 'Column B': {0: [1, 2, 3], 1: [4, 5, 6]}}
df = pd.DataFrame(d)

df = pd.DataFrame([[x] + [z] for x, y in df.values for z in y],columns=df.columns)
Nk03
  • 14,699
  • 2
  • 8
  • 22