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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With