Rahul Sharma
Rahul Sharma

Reputation: 2495

Search a dataframe column in another dataframe

I have two Dataframes like the following:

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

I want to search the values of foo in bar and if there is a match then update it in another column in df1

Expected output:

   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

I tried this but it didn't do the trick

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

How to look for a value in a column?

Upvotes: 2

Views: 2095

Answers (1)

Sayan Dey
Sayan Dey

Reputation: 856

Dataframe is known for this kind of transformation.

The one-liner is

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

Edit for new question:

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

Upvotes: 6

Related Questions