2

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 2

2

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)]
Sign up to request clarification or add additional context in comments.

Comments

2

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)]

1 Comment

Great! Thanks a lot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.