Prasad
Prasad

Reputation: 175

Comparing two dataframe values in python

I have two dataframes df1['LicId'] and df2['LicId'].

df1['LicId'] will always have one value

    LicId
0   abc1234

However df2['LicId'] will have several Ids

    LicId
0   abc1234
1   xyz2345

My task is to compare df1['LicId'] with df2['LicId'] and execute the code only if there is a match between two.

I have tried:

if df1['LicId'][0]==df2['LicId'][0]:
    remaining code

However, this will check only for abc1234 - It has to check for all the Index values of df2. Later, I may also have xyz2345 in df1.

Can someone let me know how to handle this?

Upvotes: 1

Views: 126

Answers (1)

ragesz
ragesz

Reputation: 9527

You can match values with isin():

df1 = pd.DataFrame({'LicId':['abc1234', 'a', 'b']})
df2 = pd.DataFrame({'LicId':['abc1234', 'xyz2345', 'a', 'c']})

df1:

     LicId
0  abc1234
1        a
2        b

df2:

     LicId
0  abc1234
1  xyz2345
2        a
3        c

Matching values:

if len(df2.loc[df2['LicId'].isin(df1['LicId'])]) > 0:
    print(df2.loc[df2['LicId'].isin(df1['LicId'])])
    #remaining code

Output:

     LicId
0  abc1234
2        a

Upvotes: 1

Related Questions