Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Check if a value in a df1 column is present in df2 column

Tags:

python

pandas

I have two dataframes,

df1

ID   Key
1    A
2    B
3    C
4    D

df2

ID   Key
1    D
2    C
3    B
4    E

Now, if the key in the df1 is found in df2 then the new column will have a value found else not found

the df1 with the output dataframe becomes,

  ID   Key   Result
1    A        Not Found
2    B        Found
3    C        Found
4    D        Found

How can we do this using Pandas? It's not a join/concat/merge by ID.

like image 657
Siddharth Thanga Mariappan Avatar asked Jan 26 '23 18:01

Siddharth Thanga Mariappan


2 Answers

Use numpy.where with isin:

df1['Result'] = np.where(df1['Key'].isin(df2['Key']), 'Found', 'Not Found')
print (df1)
   ID Key     Result
0   1   A  Not Found
1   2   B      Found
2   3   C      Found
3   4   D      Found
like image 111
jezrael Avatar answered Feb 14 '23 01:02

jezrael


Another solution using merge

import pandas as pd
import numpy as np

res = pd.merge(df1,df2,how="left",left_on="Key",right_on="Key",suffixes=('', '_'))

res["Result"] = np.where(pd.isna(res.ID_),"Not Found","Found")

del res["ID_"]

res

enter image description here

like image 38
Nursnaaz Avatar answered Feb 14 '23 00:02

Nursnaaz