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
|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