我想加入(或合并?)两个数据框。它们如下所示:
表 1 (= df)
index | year | country
----------------------------
0 | 1970 | NL
1 | 1970 | UK
2 | 1980 | US
3 | 1990 | NL
4 | 1990 | US
表 2 (= df_gdp)
cntry | 1970 | 1980 | 1990
-----------------------------------
NL | 5 | 3 | 0
UK | 1 | 7 | 1
US | 9 | 2 | 0
结果应为带有附加列“GDP”的表 1。应使用 Table1.year 和 Table.country 的值来查找 Table2 中的值。所以结果是:
index | year | country | GDP
--------------------------------------
0 | 1970 | NL | 5
1 | 1970 | UK | 1
2 | 1980 | US | 2
3 | 1990 | NL | 0
4 | 1990 | US | 0
我已经用 .iterrows()
编写了该函数,但正如预期的那样,这没有良好的性能。相反,我想知道结果是否也可以通过 .join()
或 .merge()
来实现。我不明白的是如何根据索引(cntry)和变化的列(年份)进行合并/连接。 .iterrows()
的代码如下所示:
# 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
最佳答案
您可以创建一个以数据帧作为参数的函数,并将其应用于 df:
def f(x):
return df_gdp.loc[x['country'],x['year']]
df['GDP']=df.apply(f, axis=1)
结果:
year country GDP
0 1970 NL 5
1 1970 UK 1
2 1980 US 2
3 1990 NL 0
4 1990 US 0
关于python - 根据索引和列合并/连接两个数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65749852/