如何比较列上的两个数据框并用其他列值替换 [英] How to compare two Dataframes on a column and replace with other column value
本文介绍了如何比较列上的两个数据框并用其他列值替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个数据帧,分别是df1和df2
I am having two data frames that are df1 and df2
id first last size
A 1978-01-01 1979-01-01 2
B 2000-01-01 2000-01-01 1
C 1998-01-01 2000-01-01 3
D 1998-01-01 1998-01-01 1
E 1999-01-01 2000-01-01 2
id token
A ZA.00
B As.11
C SD.34
输出
id first last size
ZA.00 1978-01-01 1979-01-01 2
As.11 2000-01-01 2000-01-01 1
SD.34 1998-01-01 2000-01-01 3
D 1998-01-01 1998-01-01 1
E 1999-01-01 2000-01-01 2
如果df2中存在df1 id,则令牌值将设置df1 id值. 我该如何做到这一点.
If df1 id is present in df2 then token value is to set df1 id value. How can i achieve this.
推荐答案
使用map
和fillna
:
df1['id'] = df1['id'].map(df2.set_index('id')['token']).fillna(df1['id'])
df1
输出:
id first last size
0 ZA.00 1978-01-01 1979-01-01 2
1 As.11 2000-01-01 2000-01-01 1
2 SD.34 1998-01-01 2000-01-01 3
3 D 1998-01-01 1998-01-01 1
4 E 1999-01-01 2000-01-01 2
您可以将map
与一系列用作参数.
You can use map
with a series as an argument.
这篇关于如何比较列上的两个数据框并用其他列值替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文