我想加入(或合并?)两个数据框。它们如下所示:
表 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
答案 0 :(得分:1)
您可以创建一个将数据帧作为参数的函数,并将其应用于 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
答案 1 :(得分:1)
您也可以按如下方式使用 merge
。
将索引设置为country
列,然后执行stack
操作,这样您就可以获得行中的列。然后你需要reset_index()
来获得类似于df1的数据帧结构。之后,您需要使用 set_axis()
指定列名,以便稍后在执行合并操作时进行映射。
最后只对 df1
和预处理过的 df_m
数据帧执行合并操作(默认为内连接操作)。
import pandas as pd
data1 = {
'year':['1970','1970','1980','1990','1990'],
'country':['NL','UK','US','NL','US']
}
data2 = {
'country':['NL','UK','US'],
'1970':[5,1,9],
'1980':[3,7,2],
'1990':[0,1,0]
}
df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)
# See below code
df_m = df2.set_index('country').stack().reset_index().set_axis(['country', 'year', 'GDP'], axis=1)
pd.merge(df1, df_m, on=['year','country'])
答案 2 :(得分:0)
您可以使用 melt
和 merge
:
df2.rename({'cntry': 'country'}, axis=1)\
.melt('country', var_name='year', value_name='GDP')\
.merge(df1, on=['country', 'year'])
输出:
country year GDP
0 NL 1970 5
1 UK 1970 1
2 US 1980 2
3 NL 1990 0
4 US 1990 0