1

I'm trying to merge two different DataFrames on columns which names are different but the values are the same. For example,

df1

   name subject result
0   Kim       c   pass
1   Lee  python   pass
2  Choi       c   fail

df2

    name language  score
0    Kim        c     95
1  Hwang     java     85
2    Lee   python     97
3   Park   python     80

If I run pd.merge(df1, df2, left_on='subject', right_on='language') then I get

#2 Merge stu1, stu2 by key value
  name_x subject result name_y language  score
0    Kim       c   pass    Kim        c     95
1   Choi       c   fail    Kim        c     95
2    Lee  python   pass    Lee   python     97
3    Lee  python   pass   Park   python     80

but In columns 'subject' and 'language', I want it to have only one column between them. They are redundant.

Thank you!

2
  • Aside from the question, does it really make sense to merge on 'subject', rather than 'name'? Commented Aug 13, 2021 at 7:04
  • @mozway I guess not xD, this was just provided as a learning material for pandas here. Commented Aug 13, 2021 at 8:01

1 Answer 1

5

You can try renaming the column:

out=pd.merge(df1, df2.rename(columns={'language':'subject'}),on='subject')

OR

drop column after merging:

out=pd.merge(df1, df2, left_on='subject', right_on='language').drop(columns='language')
Sign up to request clarification or add additional context in comments.

Comments

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.