How to compare values in two Pandas Dataframes?
Let’s discuss how to compare values in the Pandas dataframe. Here are the steps for comparing values in two pandas Dataframes:
Step 1 Dataframe Creation: The dataframes for the two datasets can be created using the following code:
Python3
import pandas as pd
first_Set = { 'Prod_1' : [ 'Laptop' , 'Mobile Phone' ,
'Desktop' , 'LED' ],
'Price_1' : [ 25000 , 8000 , 20000 , 35000 ]
}
df1 = pd.DataFrame(first_Set, columns = [ 'Prod_1' , 'Price_1' ])
print (df1)
second_Set = { 'Prod_2' : [ 'Laptop' , 'Mobile Phone' ,
'Desktop' , 'LED' ],
'Price_2' : [ 25000 , 10000 , 15000 , 30000 ]
}
df2 = pd.DataFrame(second_Set, columns = [ 'Prod_2' , 'Price_2' ])
print (df2)
|
Output:
Step 2 Comparison of values: You need to import numpy for the successful execution of this step. Here is the general template to perform the comparison:
df1[‘new column for the comparison results’] = np.where(condition, ‘value if true’, ‘value if false’)
Example: After execution of this code, the new column with the name Price_Matching will be formed under df1. Columns result will be displayed according to the following conditions:
- If Price_1 is equal to Price_2, then assign the value of True
- Otherwise, assign the value of False.
Python3
import numpy as np
df1[ 'Price_2' ] = df2[ 'Price_2' ]
df1[ 'Price_Matching' ] = np.where(df1[ 'Price_1' ] = = df2[ 'Price_2' ],
'True' , 'False' )
df1
|
Output:
Last Updated :
12 Jan, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...