Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas: Check if value in one df exists in any column of another DF

I have 2 DFs

DF1 & DF2

I have a column in DF1 lets call it ID. I want to check if the IDs from this column are in 2 columns from DF2 (Column names are ID1 & ID2).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have tried this approach but it’s only returning nan and false values.

DF2['Do_IDs_Exist']  = DF2[['ID1','ID2']].isin(DF1['ID'])

>Solution :

import pandas as pd

data1 = {"ID": [1, 2, 3]}
data2 = {"ID1": [1, 3, 5], "ID2": [2, 4, 6]}
DF1 = pd.DataFrame(data1)
DF1
    ID
0    1
1    2
2    3

DF2 = pd.DataFrame(data2)
DF2
    ID1 ID2
0     1   2
1     3   4
2     5   6

DF2['Do_IDs_Exist'] = (DF2['ID1'].isin(DF1['ID'])) | (DF2['ID2'].isin(DF1['ID']))
DF2
    ID1 ID2 Do_IDs_Exist
0     1   2         True
1     3   4         True
2     5   6        False

This will return True if the ID exist in one of the columns. Replace | with & if the ID should exist in both columns.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading