Pandas: merge two list columns element-by-element

Viewed 58

here is my use-case

df = pd.DataFrame({'A':[[(1,2),(3,4)],[(5,6),(7,8)]],'B':[[15,35],[55,75]]})

I would like to merge the "A" and "B" columns to get the result:

df['C'] = [[(1,2,15),(3,4,35)],[(5,6,55),(7,8,75)]]

Please feel free to propose a method with the lowest timing. Thanks

2 Answers

Just do:

df['C'] = [[ai + (bi,) for ai, bi in zip(a, b)] for a, b in df[['A', 'B']].to_numpy()]
print(df)

Output

                  A         B                         C
0  [(1, 2), (3, 4)]  [15, 35]  [(1, 2, 15), (3, 4, 35)]
1  [(5, 6), (7, 8)]  [55, 75]  [(5, 6, 55), (7, 8, 75)]

You can use double zip solution with * for unpack tuples:

df['C'] = [[(*a, b) for a, b in zip(x, y)] for x, y in zip(df['A'],df['B'])]
print (df)
                  A         B                         C
0  [(1, 2), (3, 4)]  [15, 35]  [(1, 2, 15), (3, 4, 35)]
1  [(5, 6), (7, 8)]  [55, 75]  [(5, 6, 55), (7, 8, 75)]
Related