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

Refresh

February 2019

Views

26 time

3

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. Kindly help me with this.

3 answers

0

Другой способ сделать с помощью слияния и np.where

df1['Result'] = np.where(pd.merge(df1,df2,        
                           on='key',
                 suffixes=('_x', '_match'), 
                 how='left')['id_match'].fillna('Not Found')!='Not Found','Found','Not Found')
1

Другое решение с помощью слияния

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

введите описание изображения здесь

5

Использование numpy.whereс 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