Reputation: 3041
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.
Upvotes: 4
Views: 1966
Reputation: 307
Another way to do using merge
and 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')
Upvotes: 1
Reputation: 1614
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
Upvotes: 1
Reputation: 863531
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
Upvotes: 6