Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Join on different named columns in Pandas

I have two dataframes in Pandas

left = pd.DataFrame(
    {"A": ["A0", "A1", "A2"], "B": ["B0", "B1", "B2"]}
)

right = pd.DataFrame(
    {"C": ["A0", "A1", "A2"], "D": ["D0", "D2", "D3"]}
)

How would I left join on the column A in left dataframe and column C in right dataframe?

Output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

B   D   A
B0  D0  A0
B1  D2  A1
B2  D3  A2

>Solution :

You can use merge with kwargs left_on and right_on:

pd.merge(left, right, how="left", left_on="A", right_on="C")

Output:

    A   B   C   D
0  A0  B0  A0  D0
1  A1  B1  A1  D2
2  A2  B2  A2  D3

Edit: you can drop the C column with .drop("C", axis=1)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading