-1

I have two dataframes (df1 and df2) of different size.

df1

NUTS lvl2    Code
Greece       GR
Italy        IT
Germany      DE

and df2

Ports    Code    Year
Patras    GR     2010
Lefkada   GR     2010
Bergamo   IT     2010
Palermo   IT     2011

I try to figure out how to take df2 as follow:

Ports    Code    Year    NUTS lvl2
Patras    GR     2010    Greece
Lefkada   GR     2010    Greece
Bergamo   IT     2010    Italy
Palermo   IT     2011    Italy

Could you please help me figure this out? I am trying with "where" and conditions but I have no luck so far. Ditto for inner joins.

babis
  • 11
  • 2

1 Answers1

0
df3 = df2.merge(df1, on='Code', how='left')

This is the same as a left join in SQL. You want all the rows of one dataframe (df2 in this case) and you want to match the Code column with its corresponding column associated to that Code in df1. On is a common column between the two dataframes (must be the same column name), how is left because you want all the rows of one dataframe. Whichever dataframe that you want to keep all the columns of goes first in the syntax for instance df2.merge(). An inner join in this scenario would have gotten you the same result because the column Code in df2 has GR and IT which are both in df1. Inner join takes what both columns have in common in Layman’s Terms.

8bjs110
  • 109
  • 8
  • Yep! That addressed exactly my problem. Thank you! Just to note here that the name of the columns on which the dataframes will be merged should be the same. I missed that point too. – babis Jun 04 '21 at 20:38
  • While this code may answer the question, [including an explanation](https://meta.stackoverflow.com/questions/392712/explaining-entirely-code-based-answers) of how or why this solves the problem would really help to improve the quality of your post. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – ppwater Jun 05 '21 at 07:14