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

how to compare two columns in dataframe and update a column based on matching fields

I Have two dataframe as shown below

|a|b|c|
|1|2| |
|4|5| |
|7|8| |

2nd dataframe is

|a_1|b_1|
|1  |5  |
|4  |2  |
|7  |8  | 

I want to compare two common columns (a,a_1) and update the 3rd column in my 1st dataframe Expected output is shown below

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

    |a|b|c|
    |1|2|5|
    |4|5|2|
    |7|8|8|

Is there a code to match common column and populate 3rd column kindly help on this regard.

>Solution :

import pandas as pd

d1={
    "a":(1,4,7),
    "b":(2,5,8),
}

d2={
    "a_1": (1, 4, 7),
    "b_1": (5, 2, 8)
}

df1=pd.DataFrame(d1)
df2=pd.DataFrame(d2)

c_col_list=[]

# Iterate through each entry in a and compare it to a_1
for i in range(len(df1["a"])):
    if df1["a"][i] == df2["a_1"][i]:
        # If they match, append the value to our list
        c_col_list.append(df2["b_1"][i])

# add the generated list as your c column
df1["c"]=c_col_list
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