Foreverlearning
Foreverlearning

Reputation: 41

Merging two dataframes in pandas, multiple same column names. Can't figure out syntax

I have merged my two dataframes in Pandas but I am unable to figure out how to merge two columns with same name (Country and Year). I am able to merge either Country OR Year, but, not both.

Whenever I merge say, Country, my year columns become year_x and Year_y by default, and vice versa.

Here is my syntax:

merged = pd.merge(left=df, right=df1, left_on='Year', right_on='Year')

Is there a way using this method that I can have both Year and Country? I tried to find the answer online, used different permutations in the code, such as adding both Country and Year, but I receive syntax errors every time.

Thank you for any assistance.

Upvotes: 0

Views: 179

Answers (1)

maya-ami
maya-ami

Reputation: 410

It's not quite clear what you want to achieve. If you need to merge two dataframes that have 2 identically named columns (Year and Country), something like this may help:

merged = pd.merge(left=df, right=df1, on=["Year", "Country"])

Upvotes: 1

Related Questions