Check the elements in two columns of different dataframes

Viewed 73

I have two dataframes.

Df1

Id | Name | Remarks
---------------------
1  | A    | Not bad
1  | B    | Good
2  | C    | Very bad

Df2

Id | Name | Place |Job
-----------------------
1  | A    | Can   | IT
2  |C     | Cbe   | CS
4  |L     | anc   | ME
5  | A    | cne   | IE

Output

Id | Name | Remarks  |Results
------------------------------
1  | A    | Not bad  |True
1  | B    | Good     |False
2  | C    | VeryGood |True

That is the result should be true if same id and name are present in both dataframes. I tried

df1['Results']=np.where(Df1['id','Name'].isin(Df2['Id','Name']),'true','false')

But it was not successful.

2 Answers

Use DataFrame.merge with indicator parameter and compare both values:

df = Df1[['id','Name']].merge(Df2[['Id','Name']], indicator='Results', how='left')
df['Results'] = df['Results'].eq('both')

Your solution is possible by compare index values by DataFrame.set_index with Index.isin:

df1['Results']= Df1.set_index(['id','Name']).index.isin(Df2.set_index(['id','Name']).index)

Or compare tuples from both columns:

df1['Results']= Df1[['id','Name']].agg(tuple, 1).isin(Df2[['id','Name']].agg(tuple, 1))

You can easily achieve by merge like @jezrael 's answer.

You can also achieve it with np.where,list comprehension and zip like below:

df1['Results']=np.where([str(i)+'_'+str(j)==str(k)+'_'+str(l) for i,j,k,l in zip(Df1['ID'],Df1['Name'],Df2['ID'],Df2['Name'])],True,False)
Related