在另一个数据框中搜索一个数据框列

时间:2020-08-23 05:29:30

标签: python pandas

我有两个如下所示的数据框:

df1:

   foo
0    2
1   11
2   18
3    6
4   14
5   12
6    8
7   13
8    7
9    5

df2:

   bar   date
0    2   06-01-2020
1    5   06-01-2020
2    7   06-01-2020
3    8   06-01-2020
4    3   06-01-2020

我想搜索foobar的值,如果有匹配项,则在df1的另一列中对其进行更新

预期输出:

   foo result   date
0    2   True   06-01-2020
1   11  False   24-08-2020
2   18  False   24-08-2020
3    6  False   24-08-2020
4   14  False   24-08-2020
5   12  False   24-08-2020
6    8   True   06-01-2020
7   13  False   24-08-2020
8    7   True   06-01-2020
9    5   True   06-01-2020

我尝试了这个,但是没有成功

result = []
for i in df1['foo']:
    for j in df2['bar']:
        if i==j:
            result.append('True')
        else:
            result.append('False')

如何在列中查找值?

1 个答案:

答案 0 :(得分:4)

数据框以这种转换而闻名。

单线是

df1['result'] = df1.foo.isin(df2.bar)

编辑新问题:

refdict=dict(list(zip(df2.bar, df2.date)))
df1.date=df1.foo.apply(lambda x: refdict.get(x, todaysdate))