Skip to content
Advertisement

Python Pandas – How to compare values from two columns of a dataframe to another Dataframe columns?

I have two dataframes which I need to compare between two columns based on condition and print the output. For example:

df1:

JavaScript

df2:

JavaScript

I want to write a code which compares ID column and date column between two dataframes is having a conditions like below,

  • if “ID and date is matching from df1 to df2”: print(df1[‘compare’] = ‘Both matching’)

  • if “ID is matching and date is not matching from df1 to df2” : print(df1[‘compare’] = ‘Date not matching’)

  • if “ID is Not matching from df1 to df2” : print(df1[‘compare’] = ‘ID not available’)

My result df1 should look like below:

df1 (expected result):

JavaScript

how to do this with Python pandas dataframe?

Advertisement

Answer

What I suggest you do is to use iterrows. It might not be the best idea, but still can solve your problem:

JavaScript

Output

ID Date value compare
0 248 2021-10-30 4.5 Both matching
1 249 2021-09-21 5 Date not matching
2 100 2021-02-01 3.2 ID not available
Advertisement