1

I have a Dataframe with two columns A and B (df1)

A   B
1   2
1   3
2   3

And a Dataframe (df2) with a "dictionary" describing 1, 2 and 3

O   P   Q
1   s   a
2   s   b
3   t   b

Now I want to merge the first table with the second table such that I get the following:

A   B   P1   Q1   P2   Q2
1   2    s    a    s    b
1   3    s    a    t    b
2   3    s    b    t    b

I've tried df1.merge(df2, left_on=["A","B"], right_on=["O","O"])

0

1 Answer 1

2

You have two separate merging schemes here, so you'll have to call merge twice:

(df1.merge(df2, left_on="A", right_on="O")
    .merge(df2, left_on="B", right_on="O")
    .drop(columns=['O_x', 'O_y']))

   A  B P_x Q_x P_y Q_y
0  1  2   s   a   s   b
1  1  3   s   a   t   b
2  2  3   s   b   t   b
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I thought maybe I was missing some generalization that would've allowed me to use the df2 as some sort of "dictionary" for df1. Much appreciated.

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.