Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if value from one dataframe exists in another dataframe

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.

like image 988
toceto Avatar asked May 21 '18 12:05

toceto


People also ask

How do you check if a value in one column exists in another python?

You can check if a column contains/exists a particular value (string/int), list of multiple values in pandas DataFrame by using pd. series() , in operator, pandas. series. isin() , str.

How do I compare two pandas DataFrames?

The compare method in pandas shows the differences between two DataFrames. It compares two data frames, row-wise and column-wise, and presents the differences side by side. The compare method can only compare DataFrames of the same shape, with exact dimensions and identical row and column labels.

How do you check if a value is in a series pandas?

isin() function check whether values are contained in Series. It returns a boolean Series showing whether each element in the Series matches an element in the passed sequence of values exactly.


2 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 
like image 125
piRSquared Avatar answered Oct 09 '22 11:10

piRSquared


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 
like image 44
BENY Avatar answered Oct 09 '22 12:10

BENY