I would like to join (or merge?) two dataframes. They look like the following:
Table 1 ( = df)
index | year | country
----------------------------
0 | 1970 | NL
1 | 1970 | UK
2 | 1980 | US
3 | 1990 | NL
4 | 1990 | US
Table 2 (= df_gdp)
cntry | 1970 | 1980 | 1990
-----------------------------------
NL | 5 | 3 | 0
UK | 1 | 7 | 1
US | 9 | 2 | 0
The result should be Table1 with an additional column 'GDP'. The values of Table1.year and Table.country should be used to look up the value in Table2. So the result would be:
index | year | country | GDP
--------------------------------------
0 | 1970 | NL | 5
1 | 1970 | UK | 1
2 | 1980 | US | 2
3 | 1990 | NL | 0
4 | 1990 | US | 0
I already wrote the function with .iterrows() but as expected, this does not have a good performance. Instead, I'm wondering whether the result can also be achieved by either .join() or .merge(). What I do not understand is how to merge/join based on the index (cntry) and a changing column (the year). The code of .iterrows()looks like the following:
# Add GDP data
for index, row in df.iterrows():
gdp_year = str(df.iloc[index].year)
gdp_country = str(df.iloc[index].country)
try:
df.at[index, 'GDP'] = df_gdp.loc[gdp_country][gdp_year]
except:
df.at[index, 'GDP'] = 0
df