gpt4 book ai didi

python - 基于索引和列合并/连接两个数据框

转载 作者:行者123 更新时间:2023-12-04 08:14:57 24 4
gpt4 key购买 nike

我想加入(或合并?)两个数据框。它们如下所示:
表 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com