Check if value from one dataframe exists in another dataframe

Question:

I have 2 dataframes.

Df1 = pd.DataFrame({'name': ['Marc', 'Jake', 'Sam', 'Brad']
Df2 = pd.DataFrame({'IDs': ['Jake', 'John', 'Marc', 'Tony', 'Bob']

I want to loop over every row in Df1['name'] and check if each name is somewhere in Df2['IDs'].

The result should return 1 if the name is in there, 0 if it is not like so:

Marc  1 
Jake  1
Sam   0 
Brad  0

Thank you.

Asked By: toceto

||

Answers:

Use isin

Df1.name.isin(Df2.IDs).astype(int)

0    1
1    1
2    0
3    0
Name: name, dtype: int32

Show result in data frame

Df1.assign(InDf2=Df1.name.isin(Df2.IDs).astype(int))

   name  InDf2
0  Marc      1
1  Jake      1
2   Sam      0
3  Brad      0

In a Series object

pd.Series(Df1.name.isin(Df2.IDs).values.astype(int), Df1.name.values)

Marc    1
Jake    1
Sam     0
Brad    0
dtype: int32
Answered By: piRSquared

This is one way. Convert to set for O(1) lookup and use astype(int) to represent Boolean values as integers.

values = set(Df2['IDs'])

Df1['Match'] = Df1['name'].isin(values).astype(int)
Answered By: jpp

This should do it:

Df1 = Df1.assign(result=Df1['name'].isin(Df2['IDs']).astype(int))
Answered By: zipa

By using merge

s=Df1.merge(Df2,left_on='name',right_on='IDs',how='left')
s.IDs=s.IDs.notnull().astype(int)
s
Out[68]: 
   name  IDs
0  Marc    1
1  Jake    1
2   Sam    0
3  Brad    0
Answered By: BENY
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.