将值从一个数据框映射到另一数据框

时间:2020-03-05 17:15:45

标签: python pandas

我有两个数据框。

df1 

country_code    country
US              USA
GB              Great Britain
DE              Germany

df2
country_code    date         rainfall
US              1990-01-01   235
GB              1990-01-01   235
DE              1990-01-01   235
US              1990-01-02   235
GB              1990-01-02   235
DE              1990-01-02   235
...
US              2020-01-01   235
GB              2020-01-01   235
DE              2020-01-01   235

我想知道如何将df2 country_code中的值替换为df1 country中的相应值。

即。这是期望的输出

country_code    date         rainfall
USA             1990-01-01   235
Great Britain   1990-01-01   235
Germany         1990-01-01   235
USA             1990-01-02   235
Great Britain   1990-01-02   235
Germany         1990-01-02   235
...
USA             2020-01-01   235
Great Britain   2020-01-01   235
Germany         2020-01-01   235

地图值基本上如何?

2 个答案:

答案 0 :(得分:4)

制作字典和map

mapper = dict(zip(df1.country_code, df1.country))
df2.assign(country_code=df2.country_code.map(mapper))

    country_code        date  rainfall
0            USA  1990-01-01       235
1  Great Britain  1990-01-01       235
2        Germany  1990-01-01       235
3            USA  1990-01-02       235
4  Great Britain  1990-01-02       235
5        Germany  1990-01-02       235
6            USA  2020-01-01       235
7  Great Britain  2020-01-01       235
8        Germany  2020-01-01       235

每个anky_91的建议:

我们还可以使用replace的好处是,可以将不在映射器字典中的元素保留下来

mapper = dict(zip(df1.country_code, df1.country))
df2.assign(country_code=df2.country_code.replace(mapper))

但是,我们也可以更改mapper来做相同的事情

mapper = lambda x: dict(zip(df1.country_code, df1.country)).get(x, x)
df2.assign(country_code=df2.country_code.map(mapper))

但这正是Pandas内部使用replace(-:

答案 1 :(得分:2)

如果仅显示df1,则可以使用map

df2['country_code'] = df2['country_code'].map(df1.set_index('country_code')['country'])