Home > Blockchain >  Join on different named columns in Pandas
Join on different named columns in Pandas

Time:12-02

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

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

CodePudding user response:

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)

  • Related