Given the example code below
listb = [[[1,2] , [2,3]] ,[ [3,4] , [5,6]]]
listc =[[9 , 7 ],[8 , 10] ]
lista = zip(listb , listc)
x = pandas.DataFrame(lista ,columns = ['A' , 'B'])
x.explode(['A' ,'B'])
I want to explode
A B
[[1,2] , [2,3]] [9,7]
[[3,4] , [5,6]] [8,10]
as
A B
[1,2] [9]
[2,3] [7]
[3,4] [8]
[5,6] [10]
but when I do this pandas doesn't perform any action on the dataframe .
CodePudding user response:
This works as expected (NB. explode handle multiple columns since pandas 1.3.0):
df = pd.DataFrame({'A': [[[1, 2], [2, 3]],
[[3, 4], [5, 6]]],
'B': [[9, 7], [8, 10]]})
out = df.explode(['A' ,'B'])
# A B
# 0 [1, 2] 9
# 0 [2, 3] 7
# 1 [3, 4] 8
# 1 [5, 6] 10
Only if you really want to keep lists in B, add:
out['B'] = out['B'].apply(lambda x: [x])
output:
A B
0 [1, 2] [9]
0 [2, 3] [7]
1 [3, 4] [8]
1 [5, 6] [10]
